From da336311c48d9783af96ea75f1e208e6f63f7e52 Mon Sep 17 00:00:00 2001 From: leehack Date: Mon, 23 Nov 2026 23:28:30 -0500 Subject: [PATCH 1/9] Move native qualification to LiteRT-LM v0.20.0 --- .../workflows/pr_release_qualification.yml | 16 +- README.md | 22 +- docs/asr_untimed_overlap.md | 3 +- docs/upstream_patch_audit.md | 3 +- docs/v020_qualification.md | 51 +++ native/bridge/BUILD.bazel | 12 +- native/bridge/android_gpu_c_api_test.cc | 13 + native/bridge/android_gpu_safety_v020.patch | 43 +++ .../bridge/huggingface_token_bytes_v020.patch | 246 +++++++++++++ .../litert_ios_framework_paths_v020.patch | 13 + .../litert_stage_spatial_tensors_v020.patch | 255 ++++++++++++++ native/bridge/step_zero_state_v020.patch | 38 ++ native/bridge/stream_finish_reason_v020.patch | 324 ++++++++++++++++++ .../grammar_runtime_test.cc | 4 + .../huggingface_token_bytes/shim/llguidance.h | 21 ++ .../constrained_decoding/llg_constraint.h | 3 + .../tokenizer_source_test.cc | 19 +- tools/android_gpu_safety_patch.py | 39 ++- tools/asr_litertlm_container_patch.py | 2 +- tools/asr_overlap_patch.py | 13 +- tools/build_upstream_runtime.py | 44 +-- tools/huggingface_token_bytes_patch.py | 55 ++- tools/litert_cpu_options_identifier_patch.py | 2 +- tools/litert_lm_c_api.py | 2 +- tools/litert_lm_finish_reason_smoke.py | 5 + tools/litert_lm_step_zero_smoke.py | 4 +- tools/litert_stage_spatial_tensors_patch.py | 39 ++- tools/prebuilt_overrides.py | 1 + tools/qualify_asr_untimed_overlap.py | 32 +- tools/qualify_huggingface_token_bytes.py | 15 +- tools/runtime_dependency_utils.py | 10 +- tools/step_zero_state_patch.py | 32 +- tools/stream_finish_reason_patch.py | 39 ++- tools/test_android_gpu_safety.py | 25 +- tools/test_build_upstream_runtime.py | 5 +- tools/test_huggingface_token_bytes_patch.py | 2 +- tools/test_litert_lm_finish_reason_smoke.py | 13 + tools/test_qualification_scheduling.py | 3 +- tools/test_runtime_dependency_utils.py | 27 +- tools/test_step_zero_state_patch.py | 7 +- tools/test_v0181_qualification.py | 4 +- tools/test_v020_decisions.py | 29 ++ tools/validate_runtime_dependencies.py | 14 + tools/workspace_build_patch.py | 2 +- tools/xnnpack_pf32_sme2_patch.py | 35 +- tools/xnnpack_pqs8_qc4w_sme2_patch.py | 9 + 46 files changed, 1460 insertions(+), 135 deletions(-) create mode 100644 docs/v020_qualification.md create mode 100644 native/bridge/android_gpu_safety_v020.patch create mode 100644 native/bridge/huggingface_token_bytes_v020.patch create mode 100644 native/bridge/litert_ios_framework_paths_v020.patch create mode 100644 native/bridge/litert_stage_spatial_tensors_v020.patch create mode 100644 native/bridge/step_zero_state_v020.patch create mode 100644 native/bridge/stream_finish_reason_v020.patch create mode 100644 tools/test_v020_decisions.py diff --git a/.github/workflows/pr_release_qualification.yml b/.github/workflows/pr_release_qualification.yml index ff5c31e..bc0a80c 100644 --- a/.github/workflows/pr_release_qualification.yml +++ b/.github/workflows/pr_release_qualification.yml @@ -11,9 +11,9 @@ permissions: contents: read env: - QUALIFICATION_RELEASE_TAG: v0.19.1 - QUALIFICATION_UPSTREAM_TAG: v0.19.1 - QUALIFICATION_UPSTREAM_COMMIT: 7a03724cece417f1724c923b3d527b4319730841 + QUALIFICATION_RELEASE_TAG: v0.20.0 + QUALIFICATION_UPSTREAM_TAG: v0.20.0 + QUALIFICATION_UPSTREAM_COMMIT: 95df4c2a932b4917ace66fcfef6c154e8d2a6699 jobs: preflight: @@ -104,15 +104,18 @@ jobs: - name: Qualify Android GPU preflight policy and C API refusal ordering env: LITERT_GPU_SAFETY_SOURCE: asr-upstream + LITERT_GPU_SAFETY_TAG: ${{ env.QUALIFICATION_UPSTREAM_TAG }} run: | - export PKG_CONFIG_PATH="$(brew --prefix openssl@3)/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}" + openssl_prefix="$(brew --prefix openssl@3)" + export PKG_CONFIG_PATH="$openssl_prefix/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}" pkg-config --exists openssl command -v clang++ python3 -m unittest discover -s tools -p test_android_gpu_safety.py - name: Qualify HF grammar bytes against exact tokenizer and provider sources run: | python3 tools/qualify_huggingface_token_bytes.py \ - --source-root asr-upstream --work-dir token-byte-qualification --mutations + --source-root asr-upstream --work-dir token-byte-qualification \ + --upstream-tag "$QUALIFICATION_UPSTREAM_TAG" --mutations - name: Qualify v0.19 push-source cancellation, reset and backpressure run: | python3 tools/qualify_asr_omni_input.py \ @@ -120,7 +123,8 @@ jobs: - name: Qualify real merger behaviour and kill regression mutations run: | python3 tools/qualify_asr_untimed_overlap.py \ - --source-root asr-upstream --work-dir asr-qualification --mutations + --source-root asr-upstream --work-dir asr-qualification \ + --upstream-tag "$QUALIFICATION_UPSTREAM_TAG" --mutations - uses: actions/upload-artifact@v4 if: always() with: diff --git a/README.md b/README.md index 35a471e..a698420 100644 --- a/README.md +++ b/README.md @@ -213,15 +213,14 @@ inference and ASR real-model smokes on Linux x64, Windows x64, and macOS arm64. runtime/evidence artifacts for review but has no publication input or write permission. -Pull-request qualification targets upstream `v0.19.1` at -`7a03724cece417f1724c923b3d527b4319730841`. The v0.19 line's C API 1.0 breaks -every pre-1.0 consumer; v0.19.1 keeps the v0.19.0 C ABI and every carried-patch -decision. See the [v0.19 migration and carried-patch -decisions](docs/v019_qualification.md). Android C API 1.0 source builds keep -bundled protobuf private to the runtime link; see [isolation and qualification -gates](docs/android_protobuf_isolation.md). - -The v0.19 source candidate conservatively refuses the exact Qwen3-0.6B fixture +Pull-request qualification targets upstream `v0.20.0` at +`95df4c2a932b4917ace66fcfef6c154e8d2a6699`. Consumers must admit C API +`1.1.0` before loading the candidate. See the [v0.20 qualification and carry +decisions](docs/v020_qualification.md). Android C API 1.x source builds +keep bundled protobuf private to the runtime link. See the +[isolation and qualification gates](docs/android_protobuf_isolation.md). + +The v0.20 source candidate conservatively refuses the exact Qwen3-0.6B fixture on the documented Adreno 750 driver tuple, and when this fixture's GPU safety facts are unavailable or ambiguous. It returns an actionable CPU remedy before engine creation. This source guard still needs current-candidate device @@ -432,9 +431,8 @@ turn may report 0. A missing symbol or version 0 means the runtime never reports a cause; treat it as unknown, never infer truncation from output length. Version 1 requires -the carried v0.18.0, v0.18.1, v0.19.0 or v0.19.1 patch described in -[`docs/upstream_patch_audit.md`](docs/upstream_patch_audit.md); Session-API -streams always report 0. The patch's +the [version-specific finish-reason patch](docs/upstream_patch_audit.md). +Session-API streams always report 0. The patch's `litert_lm_native_stream_chunk_get_finish_reason` can appear in the runtime's exported symbols (it does on macOS); it is internal to the bridge, not a consumer API, and may change without notice. diff --git a/docs/asr_untimed_overlap.md b/docs/asr_untimed_overlap.md index 38a0e25..e1c4093 100644 --- a/docs/asr_untimed_overlap.md +++ b/docs/asr_untimed_overlap.md @@ -29,7 +29,8 @@ for byte on every corpus; the new fallback hides their guard. The sections below record the original v0.18.0 audit. The v0.19.1 merger is byte-identical to v0.19.0, so v0.19.1 keeps the same -port and pre/postimage hashes; v0.19.2 and later still require a decision. +port and pre/postimage hashes. The v0.20.0 merger moves its text-utils include. +The same patch applies with new hashes. See [v0.20 qualification](v020_qualification.md). ## Design and scope diff --git a/docs/upstream_patch_audit.md b/docs/upstream_patch_audit.md index 720fa34..5badd77 100644 --- a/docs/upstream_patch_audit.md +++ b/docs/upstream_patch_audit.md @@ -1,6 +1,7 @@ # LiteRT-LM v0.18.0 carried-fix audit -For v0.19.0 and v0.19.1 decisions, see [v0.19 qualification](v019_qualification.md). +For later baselines, see [v0.19 qualification](v019_qualification.md) and +[v0.20 qualification](v020_qualification.md). Android C API 1.0 also has an owner [protobuf link-isolation policy](android_protobuf_isolation.md); it does not patch upstream sources or apply to v0.18 runtimes. diff --git a/docs/v020_qualification.md b/docs/v020_qualification.md new file mode 100644 index 0000000..6fd9858 --- /dev/null +++ b/docs/v020_qualification.md @@ -0,0 +1,51 @@ +# LiteRT-LM v0.20.0 qualification + +PR builds use [LiteRT-LM v0.20.0](https://github.com/google-ai-edge/LiteRT-LM/releases/tag/v0.20.0) +at `95df4c2a932b4917ace66fcfef6c154e8d2a6699`. Its `WORKSPACE` pins LiteRT +`bf49eb62406d15948261a840c9dcd8e4f13b478c`, TensorFlow +`faa06da43657488c1f7479289d11d15e03a15ba1` and ML Drift +`e9229fa80c4a99f1855721aec8282f7f4ce86fe4`. TensorFlow pins XNNPACK +`08cc38b61f7589f84e91c6e343e0f130ae3279ca`. The build verifies the declared +archive identities, Bazel repository tree hashes and patched postimages. + +## Carry decisions + +| Carry | v0.20.0 decision | +| --- | --- | +| ASR overlap | Keep the v0.19 patch and pin the new preimage and postimage. The merger's text-utils include moved to `omni/utils`. | +| Stream finish reasons | Rebase onto the shared C API callback helper and the new multi-token decode loop. Keep the finish-reason wire values and bridge ABI. | +| Hugging Face grammar | Rebase on the thread-safe tokenizer and LLGuidance v2. Keep exact ByteLevel bytes, the JSON whitespace bound and depth guard. Preserve upstream SentencePiece byte conversion and multiple EOS IDs. | +| Android Qwen3 preflight | Rebase onto the refactored engine factory. The refusal still runs before factory entry. | +| Step-zero reset and macOS lookahead | Upstream [e1f86b05](https://github.com/google-ai-edge/LiteRT-LM/commit/e1f86b05bf8a731331622a2622440e9f93d9a9f5) supplies state clearing on reset, rewind and a new context. The v0.20 carry contains only the macOS WebGPU linear-attention guard. | +| Spatial tensor staging | Rebase the LiteRT WebGPU and Vulkan carry. LiteRT `bf49eb62` predates [aa9e40cd](https://github.com/google-ai-edge/LiteRT/commit/aa9e40cd5e2d892b3a5d8579a7ec6faa696e321e). Retain the pinned LiteRT's per-environment context tracking when staging bindings. | +| XNNPACK PF32 and PQS8/QC4W | Both patches apply in their existing order to the new pin. Update the `gemm-config.c` hashes. | +| iOS Metal framework path | Rebase the legacy path carry. The default build links the accelerator statically. Retiring the path carry still requires packaged iOS evidence. | +| Android Dawn | Keep both checksum-pinned rollback binaries pending Pixel Mali qualification. The validator compares the linked Android runtime's Dawn imports with the final packaged Dawn exports. | +| Earlier retired carries | ASR container routing, the v0.18.1 Bazel repair and CPU options identifier rollback stay inactive. The tag retains the upstream SentencePiece patch and initializes GPU environment options before OpenCL. | + +## Runtime and consumer contract + +Source builds still link LiteRT in-process. Upstream removed separate LiteRT +and GPU accelerator prebuilts. The desktop and Android packages stage Dawn, +with Windows using `webgpu_dawn.dll`. The Android build selects the combined +GPU accelerator and links both the OpenCL and WebGPU samplers, preserving the +fallback when OpenCL is unavailable. + +The C API version is `1.1.0`. The existing stable status/out-parameter signatures +are preserved. New APIs include selected signatures, tool choice and ModelSync. +The experimental debugger query was replaced by an engine setting. Existing +llamadart bindings can keep their stable signatures once the ABI loader admits +1.1.x. Pin synchronizers must admit the new compatibility tag, Dawn overrides +and runtime inventory. The SwiftPM companion release must match the new runtime +line. + +The NPU executor now reads unset handwritten-component flags from bundle +metadata. Without a flag in the bundle or runtime options, those components are +disabled except for the ring-buffer KV-cache update case. The benchmark +`totalInitTime` now reports engine creation time. See the +[upstream release notes](https://github.com/google-ai-edge/LiteRT-LM/releases/tag/v0.20.0). + +The full PR qualification matrix builds all eight runtimes and checks packaged +CPU ASR, Qwen inference and C ABI on Linux x64, Windows x64 and macOS arm64. +Android device behavior, iOS device execution and Metal inference require +separate qualification. diff --git a/native/bridge/BUILD.bazel b/native/bridge/BUILD.bazel index ed46dc0..04acffc 100644 --- a/native/bridge/BUILD.bazel +++ b/native/bridge/BUILD.bazel @@ -37,7 +37,9 @@ exports_files([ "litert_cpu_options_identifier.patch", "litert_gpu_environment_destroy_callback.patch", "litert_ios_framework_paths.patch", + "litert_ios_framework_paths_v020.patch", "litert_stage_spatial_tensors.patch", + "litert_stage_spatial_tensors_v020.patch", "sentencepiece_bpe_null.patch", "stream_finish_reason.patch", "stream_finish_reason_v019.patch", @@ -90,8 +92,7 @@ config_setting( define_values = {"litert_lm_c_api_v1": "true"}, ) -# Upstream links only the OpenCL TopK sampler on Android, but its GPU -# accelerator runs on WebGPU when OpenCL cannot be loaded. +# The combined Android accelerator can select either sampler at runtime. config_setting( name = "android_webgpu_sampler", constraint_values = ["@platforms//os:android"], @@ -99,6 +100,12 @@ config_setting( ) # v0.17 moved the capabilities C implementation into //c:engine. +config_setting( + name = "android_opencl_sampler", + constraint_values = ["@platforms//os:android"], + define_values = {"litert_lm_android_opencl_sampler": "true"}, +) + config_setting( name = "capabilities_in_c_engine", define_values = {"litert_lm_capabilities_in_c_engine": "true"}, @@ -289,6 +296,7 @@ cc_binary( "//c:engine", ] + CAPABILITIES_DEPS + select({ ":android_webgpu_sampler": ["//runtime/components:top_k_webgpu_sampler_static"], + ":android_opencl_sampler": ["//runtime/components:top_k_opencl_sampler_static"], "//conditions:default": [], }), ) diff --git a/native/bridge/android_gpu_c_api_test.cc b/native/bridge/android_gpu_c_api_test.cc index 7444c33..4fe120e 100644 --- a/native/bridge/android_gpu_c_api_test.cc +++ b/native/bridge/android_gpu_c_api_test.cc @@ -31,6 +31,7 @@ struct LiteRtLmEngine { }; using LiteRtLmStatusCode = int; constexpr int kLiteRtLmStatusOk = 0; +constexpr int kLiteRtLmStatusInvalidArgument = 3; thread_local std::string last_error; thread_local int entered_factory = 0; namespace litert::lm::c { @@ -66,6 +67,18 @@ struct DisabledLog { #define LITERT_LM_C_RETURN_IF_NULL(pointer) \ if (!(pointer)) \ return 3 +bool IsValidEngineSettings(const LiteRtLmEngineSettings* settings) { + return settings && settings->settings; +} +#define LITERT_LM_C_RETURN_IF_ERROR(expr) \ + do { \ + const auto status = (expr); \ + if (!status.ok()) return litert::lm::c::ToCStatus(status); \ + } while (false) +#define LITERT_LM_C_ASSIGN_OR_RETURN(lhs, expr) \ + auto status_or = (expr); \ + if (!status_or.ok()) return litert::lm::c::ToCStatus(status_or.status()); \ + lhs = *std::move(status_or) // System headers are already parsed; this selects only the injected C API body. #define __ANDROID__ 1 // PRODUCTION_ENGINE_CREATE diff --git a/native/bridge/android_gpu_safety_v020.patch b/native/bridge/android_gpu_safety_v020.patch new file mode 100644 index 0000000..c292a2f --- /dev/null +++ b/native/bridge/android_gpu_safety_v020.patch @@ -0,0 +1,43 @@ +diff --git a/c/BUILD b/c/BUILD +index cca1092c..7aba4ef7 100644 +--- a/c/BUILD ++++ b/c/BUILD +@@ -45,6 +45,7 @@ exports_files([ + ]) + + ENGINE_LITE_COMMON_DEPS = [ ++ "//bridge:litert_lm_android_gpu_preflight", + ":c_api_internal", + ":engine_internal", + ":error_reporter", +diff --git a/c/engine.cc b/c/engine.cc +index 4e216335..46bfb4ba 100644 +--- a/c/engine.cc ++++ b/c/engine.cc +@@ -13,6 +13,7 @@ + // limitations under the License. + + #include "c/engine.h" ++#include "bridge/litert_lm_android_gpu_preflight.h" + + #include + #include +@@ -1041,9 +1042,17 @@ LiteRtLmStatusCode litert_lm_engine_create( + if (!IsValidEngineSettings(settings)) { + return kLiteRtLmStatusInvalidArgument; + } ++#if defined(__ANDROID__) ++ auto guarded_settings = *settings->settings; ++ LITERT_LM_C_RETURN_IF_ERROR( ++ litert_lm_native::PrepareAndroidGpuSafety(guarded_settings)); ++ const auto& selected_settings = guarded_settings; ++#else ++ const auto& selected_settings = *settings->settings; ++#endif + LITERT_LM_C_ASSIGN_OR_RETURN( + std::unique_ptr engine, +- EngineFactory::CreateDefault(*settings->settings)); ++ EngineFactory::CreateDefault(selected_settings)); + auto c_engine = std::make_unique(); + c_engine->engine = std::move(engine); + *out_engine = c_engine.release(); diff --git a/native/bridge/huggingface_token_bytes_v020.patch b/native/bridge/huggingface_token_bytes_v020.patch new file mode 100644 index 0000000..8e33d38 --- /dev/null +++ b/native/bridge/huggingface_token_bytes_v020.patch @@ -0,0 +1,246 @@ +diff --git a/runtime/components/constrained_decoding/BUILD b/runtime/components/constrained_decoding/BUILD +index 22ec1a94..bbc89c06 100644 +--- a/runtime/components/constrained_decoding/BUILD ++++ b/runtime/components/constrained_decoding/BUILD +@@ -344,6 +344,7 @@ cc_library( + "//conditions:default": [], + }), + deps = [ ++ "@nlohmann_json//:json", + ":constraint", + ":constraint_provider", + ":constraint_provider_config", +diff --git a/runtime/components/constrained_decoding/llg_constraint_provider.cc b/runtime/components/constrained_decoding/llg_constraint_provider.cc +index b707669e..652a5a8a 100644 +--- a/runtime/components/constrained_decoding/llg_constraint_provider.cc ++++ b/runtime/components/constrained_decoding/llg_constraint_provider.cc +@@ -41,6 +41,7 @@ + #include "runtime/components/constrained_decoding/llg_constraint.h" + #include "runtime/components/constrained_decoding/llg_constraint_config.h" + #include "llguidance.h" ++#include "nlohmann/json.hpp" // from @nlohmann_json + + namespace litert::lm { + namespace { +@@ -94,6 +95,52 @@ bool TokenizesVerbatim(Tokenizer& tokenizer, + return true; + } + ++bool JsonNestingWithinPreprocessingLimit(absl::string_view text) { ++ constexpr size_t kMaxDepth = 128; ++ size_t depth = 0; ++ bool in_string = false; ++ bool escaped = false; ++ for (const char ch : text) { ++ if (in_string) { ++ if (escaped) escaped = false; ++ else if (ch == '\\') escaped = true; ++ else if (ch == '"') in_string = false; ++ } else if (ch == '"') { ++ in_string = true; ++ } else if (ch == '{' || ch == '[') { ++ if (++depth > kMaxDepth) return false; ++ } else if (ch == '}' || ch == ']') { ++ if (depth == 0) return false; ++ --depth; ++ } ++ } ++ return true; ++} ++ ++std::string WithDefaultJsonWhitespace(absl::string_view text) { ++ // Deep DOM insertion/serialization/destruction can exhaust the C++ stack. ++ // Let llguidance validate overdeep input unchanged before building a DOM. ++ if (!JsonNestingWithinPreprocessingLimit(text)) return std::string(text); ++ auto schema = nlohmann::ordered_json::parse(text.begin(), text.end(), nullptr, ++ false); ++ if (schema.is_boolean()) { ++ schema = nlohmann::ordered_json{{"allOf", {schema}}}; ++ } ++ if (!schema.is_object()) return std::string(text); ++ if (!schema.contains("x-guidance")) { ++ schema["x-guidance"] = nlohmann::ordered_json::object(); ++ } ++ auto& options = schema["x-guidance"]; ++ if (!options.is_object() || options.contains("whitespace_pattern") || ++ options.contains("whitespace_flexible")) { ++ return std::string(text); ++ } ++ // An unlimited skip lets greedy decoding spend the entire output budget on ++ // insignificant whitespace. The once-per-gap bound preserves JSON values. ++ options["whitespace_pattern"] = R"([\x20\x0A\x0D\x09]{1,8})"; ++ return schema.dump(); ++} ++ + ::LlgConstraint* CreateLlgConstraint(LlgConstraintInit* llg_constraint_init, + absl::string_view constraint_string, + LlgConstraintType constraint_type) { +@@ -101,9 +148,10 @@ bool TokenizesVerbatim(Tokenizer& tokenizer, + case LlgConstraintType::kRegex: + return llg_new_constraint_regex(llg_constraint_init, + constraint_string.data()); +- case LlgConstraintType::kJsonSchema: +- return llg_new_constraint_json(llg_constraint_init, +- constraint_string.data()); ++ case LlgConstraintType::kJsonSchema: { ++ const std::string schema = WithDefaultJsonWhitespace(constraint_string); ++ return llg_new_constraint_json(llg_constraint_init, schema.c_str()); ++ } + case LlgConstraintType::kLark: + return llg_new_constraint_lark(llg_constraint_init, + constraint_string.data()); +@@ -123,13 +171,25 @@ LlgConstraintProvider::Create(const Tokenizer& tokenizer, + "LlGuidanceConfig::eos_ids must not be empty."); + } + +- std::vector tokens = tokenizer.GetTokens(); ++ const auto raw_tokens = tokenizer.GetTokens(); ++ std::vector tokens = raw_tokens; ++ const bool use_hf_bytes = ++ tokenizer.GetTokenizerType() == ::litert::support::TokenizerType::kHuggingFace; ++ if (use_hf_bytes) { ++ auto token_bytes_or = tokenizer.GetTokenBytes(); ++ if (!token_bytes_or.ok()) return token_bytes_or.status(); ++ tokens = *std::move(token_bytes_or); ++ if (tokens.size() != raw_tokens.size()) { ++ return absl::InvalidArgumentError("Token bytes must preserve vocabulary IDs."); ++ } ++ } + + absl::flat_hash_set special_tokens_set( + llg_config.special_tokens.begin(), llg_config.special_tokens.end()); + std::vector is_special(tokens.size()); + for (size_t i = 0; i < tokens.size(); ++i) { +- is_special[i] = special_tokens_set.contains(tokens[i]); ++ is_special[i] = tokenizer.IsSpecialToken(i) || ++ special_tokens_set.contains(raw_tokens[i]); + } + // EOS tokens are special too, so that the constraint can't match them as + // text. Otherwise text could contain an EOS token, which ends generation +@@ -148,8 +208,9 @@ LlgConstraintProvider::Create(const Tokenizer& tokenizer, + if (is_special[i]) { + // Special tokens need to be prefixed with 0xFF. + // https://github.com/guidance-ai/llguidance/blob/main/docs/special_tokens.md ++ tokens[i] = raw_tokens[i]; + tokens[i].insert(0, 1, '\xff'); +- } else { ++ } else if (!use_hf_bytes) { + tokens[i] = TokenToBytes(tokens[i]); + } + } +diff --git a/support/tokenizer/BUILD b/support/tokenizer/BUILD +index c07834f9..d71191b4 100644 +--- a/support/tokenizer/BUILD ++++ b/support/tokenizer/BUILD +@@ -97,6 +97,7 @@ cc_library( + hdrs = ["huggingface_tokenizer.h"], + linkstatic = 1, + deps = [ ++ "//bridge:huggingface_token_bytes", + ":tokenizer", + "@com_google_absl//absl/base:core_headers", + "@com_google_absl//absl/base:nullability", +@@ -115,6 +116,7 @@ cc_library( + defines = ["ENABLE_HUGGINGFACE_TOKENIZER"], + linkstatic = 1, + deps = [ ++ "//bridge:huggingface_token_bytes", + ":tokenizer", + "@com_google_absl//absl/base:core_headers", + "@com_google_absl//absl/base:nullability", +diff --git a/support/tokenizer/huggingface_tokenizer.cc b/support/tokenizer/huggingface_tokenizer.cc +index 9d87f628..cdd94d6a 100644 +--- a/support/tokenizer/huggingface_tokenizer.cc ++++ b/support/tokenizer/huggingface_tokenizer.cc +@@ -57,7 +57,7 @@ HuggingFaceTokenizer::CreateFromJson(const std::string& json) { + size_t vocab_size = 0; + tokenizers_get_vocab_size(handle, &vocab_size); + return absl::WrapUnique( +- new HuggingFaceTokenizer(handle, static_cast(vocab_size))); ++ new HuggingFaceTokenizer(handle, static_cast(vocab_size), json)); + } + + // Encodes the given text into a TensorBuffer of token ids. +@@ -116,6 +116,19 @@ std::vector HuggingFaceTokenizer::GetTokens() const { + return tokens; + } + ++absl::StatusOr> HuggingFaceTokenizer::GetTokenBytes() const { ++ if (!token_bytes_.supported()) { ++ return absl::UnimplementedError( ++ "HuggingFace constrained decoding requires a ByteLevel decoder; " ++ "this tokenizer decoder has no lossless token-byte adapter."); ++ } ++ auto tokens = GetTokens(); ++ for (size_t id = 0; id < tokens.size(); ++id) { ++ tokens[id] = token_bytes_.TokenBytes(tokens[id], id); ++ } ++ return tokens; ++} ++ + int HuggingFaceTokenizer::GetVocabSize() const { return vocab_size_; } + + } // namespace litert::support +diff --git a/support/tokenizer/huggingface_tokenizer.h b/support/tokenizer/huggingface_tokenizer.h +index ea63108c..2f96dc89 100644 +--- a/support/tokenizer/huggingface_tokenizer.h ++++ b/support/tokenizer/huggingface_tokenizer.h +@@ -27,6 +27,7 @@ + #include "absl/synchronization/mutex.h" // from @com_google_absl + #include "absl/types/span.h" // from @com_google_absl + #include "support/tokenizer/tokenizer.h" ++#include "bridge/huggingface_token_bytes.h" + + namespace litert::support { + +@@ -64,12 +65,19 @@ class HuggingFaceTokenizer : public Tokenizer { + + std::vector GetTokens() const override; + ++ absl::StatusOr> GetTokenBytes() const override; ++ ++ bool IsSpecialToken(int token_id) const override { ++ return token_bytes_.IsSpecialToken(token_id); ++ } ++ + int GetVocabSize() const override; + + private: + // Constructor. +- HuggingFaceTokenizer(TokenizerHandle absl_nonnull handle, int vocab_size) +- : vocab_size_(vocab_size), handle_(handle) {} ++ HuggingFaceTokenizer(TokenizerHandle absl_nonnull handle, int vocab_size, ++ const std::string& json) ++ : vocab_size_(vocab_size), handle_(handle), token_bytes_(json) {} + + // Vocabulary size, read once at creation (the vocabulary is immutable). + const int vocab_size_; +@@ -81,6 +89,7 @@ class HuggingFaceTokenizer : public Tokenizer { + + // HuggingFace processor. + TokenizerHandle absl_nonnull handle_ ABSL_GUARDED_BY(mutex_); ++ HuggingFaceTokenBytes token_bytes_; + }; + + } // namespace litert::support +diff --git a/support/tokenizer/tokenizer.h b/support/tokenizer/tokenizer.h +index ce44bb98..e7d457af 100644 +--- a/support/tokenizer/tokenizer.h ++++ b/support/tokenizer/tokenizer.h +@@ -80,5 +80,16 @@ class Tokenizer { + // Returns the list of tokens in the tokenizer. + virtual std::vector GetTokens() const = 0; + ++ // Returns llguidance vocabulary entries in token-ID order. Byte-level ++ // tokenizers override this with lossless bytes, including NUL and partial ++ // UTF-8. Legacy providers retain their existing raw-token mapping. ++ virtual absl::StatusOr> GetTokenBytes() const { ++ return GetTokens(); ++ } ++ ++ // Identifies tokenizer-declared control tokens by ID, independently of their ++ // spelling. Constraint-provider configuration can declare more special tokens. ++ virtual bool IsSpecialToken(int) const { return false; } ++ + // Returns the size of the vocabulary. + virtual int GetVocabSize() const = 0; diff --git a/native/bridge/litert_ios_framework_paths_v020.patch b/native/bridge/litert_ios_framework_paths_v020.patch new file mode 100644 index 0000000..83e8d21 --- /dev/null +++ b/native/bridge/litert_ios_framework_paths_v020.patch @@ -0,0 +1,13 @@ +diff --git a/litert/runtime/accelerators/gpu_registry.cc b/litert/runtime/accelerators/gpu_registry.cc +--- a/litert/runtime/accelerators/gpu_registry.cc ++++ b/litert/runtime/accelerators/gpu_registry.cc +@@ -56,7 +56,8 @@ + + #elif TARGET_OS_IPHONE + #if LITERT_HAS_METAL_SUPPORT +- "libLiteRtMetalAccelerator" SO_EXT, ++ "@executable_path/Frameworks/LiteRtMetalAccelerator.framework/" ++ "LiteRtMetalAccelerator", + // Inside an Apple framework bundle the executable is named after the + // bundle, so the accelerator ships as + // LiteRtMetalAccelerator.framework/LiteRtMetalAccelerator. diff --git a/native/bridge/litert_stage_spatial_tensors_v020.patch b/native/bridge/litert_stage_spatial_tensors_v020.patch new file mode 100644 index 0000000..91db30e --- /dev/null +++ b/native/bridge/litert_stage_spatial_tensors_v020.patch @@ -0,0 +1,255 @@ +diff --git a/ml_drift_delegate/delegate/gpu_backend_vulkan.cc b/ml_drift_delegate/delegate/gpu_backend_vulkan.cc +--- a/ml_drift_delegate/delegate/gpu_backend_vulkan.cc ++++ b/ml_drift_delegate/delegate/gpu_backend_vulkan.cc +@@ -380,16 +380,42 @@ + num_nodes_per_command_buffer_(kDefaultMaxNumNodesPerCommandBuffer) {} + + GpuInferenceContextVulkan::~GpuInferenceContextVulkan() { ++ JoinNextCommandBuffersThread(); ++ if (post_dispatch_event_ != nullptr) { ++ post_dispatch_event_->Release(post_dispatch_event_); ++ } ++} ++ ++void GpuInferenceContextVulkan::JoinNextCommandBuffersThread() { + if (next_command_buffers_thread_) { + next_command_buffers_thread_->join(); ++ next_command_buffers_thread_.reset(); + } +- if (post_dispatch_event_ != nullptr) { +- post_dispatch_event_->Release(post_dispatch_event_); ++} ++ ++absl::Status GpuInferenceContextVulkan::FlushPendingSpatialTensors() { ++ if (pending_spatial_tensors_.empty()) { ++ return absl::OkStatus(); + } ++ auto pending = std::move(pending_spatial_tensors_); ++ pending_spatial_tensors_.clear(); ++ absl::MutexLock lock(ctx_mutex_); ++ for (const auto& [id, tensor] : pending) { ++ ABSL_RETURN_IF_ERROR(ctx_.SetTensor(id, tensor)); ++ } ++ return absl::OkStatus(); + } + + absl::StatusOr<::ml_drift::GpuSpatialTensor*> + GpuInferenceContextVulkan::GetSpatialTensor(::ml_drift::ValueId id) { ++ if (auto it = pending_spatial_tensors_.find(id); ++ it != pending_spatial_tensors_.end()) { ++ if (it->second == nullptr) { ++ return absl::NotFoundError( ++ absl::StrCat("No GPU tensor allocated for tensor id ", id, ".")); ++ } ++ return it->second; ++ } + absl::MutexLock lock(ctx_mutex_); + auto* tensor = ctx_.GetTensor(id); + if (tensor == nullptr) { +@@ -403,8 +429,13 @@ + + absl::Status GpuInferenceContextVulkan::BindSpatialTensor( + ::ml_drift::ValueId id, ::ml_drift::GpuSpatialTensor* tensor) { ++ auto* vk_tensor = static_cast(tensor); ++ if (!next_command_buffers_.empty()) { ++ pending_spatial_tensors_[id] = vk_tensor; ++ return absl::OkStatus(); ++ } + absl::MutexLock lock(ctx_mutex_); +- return ctx_.SetTensor(id, static_cast(tensor)); ++ return ctx_.SetTensor(id, vk_tensor); + } + + absl::Status GpuInferenceContextVulkan::WriteDataToWeightTensor( +@@ -436,9 +467,8 @@ + return shared_env.AddToPendingCommandBuffers(std::move(command_buffers)); + } + +- if (next_command_buffers_thread_) { +- next_command_buffers_thread_->join(); +- } ++ JoinNextCommandBuffersThread(); ++ ABSL_RETURN_IF_ERROR(FlushPendingSpatialTensors()); + + if (last_ctx_ != this) { + last_ctx_ = this; +@@ -557,6 +587,11 @@ + + absl::Status GpuInferenceContextVulkan::SetCommandBufferHint( + int num_nodes_per_command_buffer) { ++ // Must be called before any Dispatch() call. ++ if (next_command_buffers_thread_ != nullptr) { ++ return absl::FailedPreconditionError( ++ "SetCommandBufferHint must be called before any Dispatch() call."); ++ } + num_nodes_per_command_buffer_ = num_nodes_per_command_buffer; + return absl::OkStatus(); + } +diff --git a/ml_drift_delegate/delegate/gpu_backend_vulkan.h b/ml_drift_delegate/delegate/gpu_backend_vulkan.h +--- a/ml_drift_delegate/delegate/gpu_backend_vulkan.h ++++ b/ml_drift_delegate/delegate/gpu_backend_vulkan.h +@@ -228,6 +228,7 @@ + const override; + absl::Status ReportMemoryBenchmarkIfEnabled( + const ::ml_drift::CreateGpuModelInfo& create_info) override; ++ // Must be called before any Dispatch() call. + absl::Status SetCommandBufferHint(int num_nodes_per_command_buffer) override; + + // Underlying Vulkan inference context. +@@ -237,9 +238,17 @@ + } + + private: ++ void JoinNextCommandBuffersThread(); ++ absl::Status FlushPendingSpatialTensors(); ++ + GpuBackendVulkan* const backend_; + absl::Mutex ctx_mutex_; + ::ml_drift::syrtis::VulkanInferenceContext ctx_; ++ // Spatial tensor bindings staged while background command buffer preparation ++ // is enabled, applied to ctx_ once next_command_buffers_thread_ finishes. ++ absl::flat_hash_map<::ml_drift::ValueId, ++ ::ml_drift::syrtis::VulkanSpatialTensor*> ++ pending_spatial_tensors_; + + // Command buffers prepared ahead to reduce the overhead of command buffer + // preparation. +@@ -251,6 +260,9 @@ + // Whether next_command_buffers_ is ready to use. It's set to true when + // all next_command_buffers_ are prepared. + bool next_command_buffers_ready_ = false; ++ // Prepares next_command_buffers_ in parallel with the current Dispatch() ++ // call. JoinNextCommandBuffersThread() joins and resets it before flushing ++ // staged bindings to ctx_ or touching next_command_buffers_ again. + std::unique_ptr next_command_buffers_thread_; + + // Static member var indicating the last context which built the command +diff --git a/ml_drift_delegate/delegate/gpu_backend_webgpu.cc b/ml_drift_delegate/delegate/gpu_backend_webgpu.cc +--- a/ml_drift_delegate/delegate/gpu_backend_webgpu.cc ++++ b/ml_drift_delegate/delegate/gpu_backend_webgpu.cc +@@ -422,14 +422,40 @@ + num_nodes_per_command_encoder_(kNumNodesPerCommandEncoder) {} + + GpuInferenceContextWebGpu::~GpuInferenceContextWebGpu() { ++ JoinNextCommandBuffersThread(); ++ SharedWebGpuEnv::Get().ClearLastContextIfMatched(&backend_->wgpu_env(), this); ++} ++ ++void GpuInferenceContextWebGpu::JoinNextCommandBuffersThread() { + if (next_command_buffers_thread_) { + next_command_buffers_thread_->join(); ++ next_command_buffers_thread_.reset(); + } +- SharedWebGpuEnv::Get().ClearLastContextIfMatched(&backend_->wgpu_env(), this); + } + ++absl::Status GpuInferenceContextWebGpu::FlushPendingSpatialTensors() { ++ if (pending_spatial_tensors_.empty()) { ++ return absl::OkStatus(); ++ } ++ auto pending = std::move(pending_spatial_tensors_); ++ pending_spatial_tensors_.clear(); ++ absl::MutexLock lock(backend_->memory_manager_mutex()); ++ for (const auto& [id, tensor] : pending) { ++ ABSL_RETURN_IF_ERROR(ctx_->SetTensor(id, tensor)); ++ } ++ return absl::OkStatus(); ++} ++ + absl::StatusOr<::ml_drift::webgpu::SpatialTensor*> + GpuInferenceContextWebGpu::GetSpatialTensorInternal(::ml_drift::ValueId id) { ++ if (auto it = pending_spatial_tensors_.find(id); ++ it != pending_spatial_tensors_.end()) { ++ if (it->second == nullptr) { ++ return absl::NotFoundError( ++ absl::StrCat("No GPU tensor allocated for tensor id ", id, ".")); ++ } ++ return it->second; ++ } + absl::MutexLock lock(backend_->memory_manager_mutex()); + auto* tensor = ctx_->GetTensor(id); + if (tensor == nullptr) { +@@ -448,9 +474,13 @@ + + absl::Status GpuInferenceContextWebGpu::BindSpatialTensor( + ::ml_drift::ValueId id, ::ml_drift::GpuSpatialTensor* tensor) { ++ auto* wgpu_tensor = static_cast<::ml_drift::webgpu::SpatialTensor*>(tensor); ++ if (!next_command_buffers_.empty()) { ++ pending_spatial_tensors_[id] = wgpu_tensor; ++ return absl::OkStatus(); ++ } + absl::MutexLock lock(backend_->memory_manager_mutex()); +- return ctx_->SetTensor( +- id, static_cast<::ml_drift::webgpu::SpatialTensor*>(tensor)); ++ return ctx_->SetTensor(id, wgpu_tensor); + } + + absl::Status GpuInferenceContextWebGpu::WriteDataToWeightTensor( +@@ -529,9 +559,8 @@ + /*submit_command_buffers=*/true); + } + +- if (next_command_buffers_thread_) { +- next_command_buffers_thread_->join(); +- } ++ JoinNextCommandBuffersThread(); ++ ABSL_RETURN_IF_ERROR(FlushPendingSpatialTensors()); + + SharedWebGpuEnv& shared_env = SharedWebGpuEnv::Get(); + const ::ml_drift::webgpu::ExecutionEnvironment* env = &backend_->wgpu_env(); +@@ -674,6 +703,11 @@ + + absl::Status GpuInferenceContextWebGpu::SetCommandBufferHint( + int num_nodes_per_command_encoder) { ++ // Must be called before any Dispatch() call. ++ if (next_command_buffers_thread_ != nullptr) { ++ return absl::FailedPreconditionError( ++ "SetCommandBufferHint must be called before any Dispatch() call."); ++ } + num_nodes_per_command_encoder_ = num_nodes_per_command_encoder; + return absl::OkStatus(); + } +diff --git a/ml_drift_delegate/delegate/gpu_backend_webgpu.h b/ml_drift_delegate/delegate/gpu_backend_webgpu.h +--- a/ml_drift_delegate/delegate/gpu_backend_webgpu.h ++++ b/ml_drift_delegate/delegate/gpu_backend_webgpu.h +@@ -256,6 +256,7 @@ + const override; + absl::Status ReportMemoryBenchmarkIfEnabled( + const ::ml_drift::CreateGpuModelInfo& create_info) override; ++ // Must be called before any Dispatch() call. + absl::Status SetCommandBufferHint(int num_nodes_per_command_encoder) override; + + // Underlying WebGPU inference context. +@@ -267,6 +268,8 @@ + private: + absl::StatusOr<::ml_drift::webgpu::SpatialTensor*> GetSpatialTensorInternal( + ::ml_drift::ValueId id); ++ void JoinNextCommandBuffersThread(); ++ absl::Status FlushPendingSpatialTensors(); + // Prepares command buffers for Dispatch() call. + absl::Status PrepareCommandBuffers( + std::vector& command_buffers, +@@ -281,6 +284,10 @@ + GpuBackendWebGpu* const backend_; + std::unique_ptr<::ml_drift::webgpu::InferenceContext> ctx_; + std::vector> async_upload_notifications_; ++ // Spatial tensor bindings staged while background command buffer preparation ++ // is enabled, applied to ctx_ once next_command_buffers_thread_ finishes. ++ absl::flat_hash_map<::ml_drift::ValueId, ::ml_drift::webgpu::SpatialTensor*> ++ pending_spatial_tensors_; + + // Command buffers prepared in advance for the next Dispatch() call. + std::vector> next_command_buffers_; +@@ -292,9 +299,8 @@ + // all next_command_buffers_ are prepared. + bool next_command_buffers_ready_ = false; + // Prepares next_command_buffers_ in parallel with the current Dispatch() +- // call. It is only accessed by the thread calling Dispatch(), which joins it +- // before touching next_command_buffers_ again, so no synchronization is +- // needed; see SharedWebGpuEnv for how a Dispatch() by a different context on +- // the same environment is handled. ++ // call. JoinNextCommandBuffersThread() joins and resets it before flushing ++ // staged bindings to ctx_ or touching next_command_buffers_ again. ++ // SharedWebGpuEnv tracks context changes per environment. + std::unique_ptr next_command_buffers_thread_; + }; diff --git a/native/bridge/step_zero_state_v020.patch b/native/bridge/step_zero_state_v020.patch new file mode 100644 index 0000000..d624843 --- /dev/null +++ b/native/bridge/step_zero_state_v020.patch @@ -0,0 +1,38 @@ +diff --git a/runtime/executor/llm_litert_compiled_model_executor.cc b/runtime/executor/llm_litert_compiled_model_executor.cc +index eb57d957..fb15df70 100644 +--- a/runtime/executor/llm_litert_compiled_model_executor.cc ++++ b/runtime/executor/llm_litert_compiled_model_executor.cc +@@ -57,6 +57,7 @@ + #include "litert/cc/litert_tensor_buffer.h" // from @litert + #include "litert/cc/litert_tensor_buffer_types.h" // from @litert + #if defined(__APPLE__) ++#include + #include "litert/cc/options/litert_gpu_options.h" // from @litert + #endif // defined(__APPLE__) + #include "runtime/components/constrained_decoding/constrained_decoder.h" +@@ -1955,6 +1956,25 @@ absl::Status LlmLiteRtCompiledModelExecutorBase::InitializeSampler( + sampler_handles_input = + executor_settings_.GetAdvancedSettings()->sampler_handles_input; + } ++#if defined(__APPLE__) && TARGET_OS_OSX ++ if (sampler_handles_input && sampler_backend == Backend::GPU && ++ executor_settings_.GetBackend() == Backend::GPU && ++ executor_metadata_ != nullptr && ++ executor_metadata_->has_llm_executor_metadata() && ++ absl::c_any_of( ++ executor_metadata_->llm_executor_metadata().state_buffers(), ++ [](const proto::StateBuffer& state) { ++ return state.type() == proto::StateBuffer::TYPE_LINEAR_ATTENTION; ++ })) { ++ const auto options = env_.GetOptions(); ++ if (options.HasValue() && ++ options->GetOption(EnvironmentOptions::Tag::kWebGpuDevice).HasValue()) { ++ sampler_handles_input = false; ++ ABSL_LOG(INFO) << "Using executor-managed decode inputs for WebGPU " ++ "linear attention on macOS."; ++ } ++ } ++#endif + const AttentionMaskParams sampler_attn_params = + GetAttentionMaskParams(executor_metadata_); + const TensorBuffer* decode_attn_mask_buffer = diff --git a/native/bridge/stream_finish_reason_v020.patch b/native/bridge/stream_finish_reason_v020.patch new file mode 100644 index 0000000..916cfcf --- /dev/null +++ b/native/bridge/stream_finish_reason_v020.patch @@ -0,0 +1,324 @@ +diff --git a/c/c_api_internal.h b/c/c_api_internal.h +index d19e38cb..2cadd626 100644 +--- a/c/c_api_internal.h ++++ b/c/c_api_internal.h +@@ -70,8 +70,9 @@ void SetExecutorCacheDirs( + // Invokes a C streaming callback with a single `LiteRtLmStreamChunk`. + inline void EmitStreamChunk(LiteRtLmStreamCallback callback, + void* callback_data, const char* text, +- bool is_final, const char* error_msg) { +- LiteRtLmStreamChunk chunk{text, is_final, error_msg}; ++ bool is_final, const char* error_msg, ++ int finish_reason = 0) { ++ LiteRtLmStreamChunk chunk{text, is_final, error_msg, finish_reason}; + callback(callback_data, &chunk); + } + +diff --git a/c/conversation.cc b/c/conversation.cc +index 1e1f23a4..eaeada6d 100644 +--- a/c/conversation.cc ++++ b/c/conversation.cc +@@ -54,18 +54,47 @@ using ::litert::lm::c::IsValidEngine; + using ::litert::lm::c::IsValidSessionConfig; + using ::litert::lm::c::RawEnumValue; + ++// litert-lm-native stream_proxy finish-reason wire values. ++enum FinishReason : int { ++ kFinishReasonUnknown = 0, ++ kFinishReasonStop = 1, ++ kFinishReasonLength = 2, ++ kFinishReasonContextExhausted = 3, ++ kFinishReasonCancelled = 4, ++ kFinishReasonError = 5, ++}; ++ ++int ToFinishReason(litert::lm::DecodeStopReason reason) { ++ switch (reason) { ++ case litert::lm::DecodeStopReason::kStopToken: ++ return kFinishReasonStop; ++ case litert::lm::DecodeStopReason::kMaxOutputTokens: ++ return kFinishReasonLength; ++ case litert::lm::DecodeStopReason::kMaxNumTokens: ++ return kFinishReasonContextExhausted; ++ case litert::lm::DecodeStopReason::kUnspecified: ++ return kFinishReasonUnknown; ++ } ++ return kFinishReasonUnknown; ++} ++ + absl::AnyInvocable)> +-CreateConversationCallback(LiteRtLmStreamCallback callback, void* user_data) { +- return [callback, user_data](absl::StatusOr message) { ++CreateConversationCallback(LiteRtLmStreamCallback callback, void* user_data, ++ const litert::lm::Conversation* conversation) { ++ return [callback, user_data, ++ conversation](absl::StatusOr message) { + if (!message.ok()) { + std::string error_str = message.status().ToString(); + EmitStreamChunk(callback, user_data, /*text=*/nullptr, /*is_final=*/true, +- error_str.c_str()); ++ error_str.c_str(), absl::IsCancelled(message.status()) ++ ? kFinishReasonCancelled ++ : kFinishReasonError); + return; + } + if (message->empty()) { // End of stream marker + EmitStreamChunk(callback, user_data, /*text=*/nullptr, /*is_final=*/true, +- /*error_msg=*/nullptr); ++ /*error_msg=*/nullptr, ++ ToFinishReason(conversation->GetLastDecodeStopReason())); + } else { + std::string json_str = message->dump(); + EmitStreamChunk(callback, user_data, json_str.c_str(), /*is_final=*/false, +@@ -743,11 +772,19 @@ LiteRtLmStatusCode litert_lm_conversation_send_message_stream( + conversation->conversation.get(), extra_context, optional_args); + + LITERT_LM_C_RETURN_IF_ERROR(conversation->conversation->SendMessageAsync( +- json_message, CreateConversationCallback(callback, callback_data), ++ json_message, ++ CreateConversationCallback(callback, callback_data, ++ conversation->conversation.get()), + std::move(litert_lm_optional_args))); + return kLiteRtLmStatusOk; + } + ++// Not part of the upstream C API: the litert-lm-native bridge reads it. ++int litert_lm_native_stream_chunk_get_finish_reason( ++ const LiteRtLmStreamChunk* chunk) { ++ return chunk == nullptr ? kFinishReasonUnknown : chunk->finish_reason; ++} ++ + LiteRtLmStatusCode litert_lm_conversation_render_message_to_string( + LiteRtLmConversation* conversation, const char* message_json, + const char** out_text) { +diff --git a/c/engine_internal.h b/c/engine_internal.h +index 8d3ad14e..2966aa58 100644 +--- a/c/engine_internal.h ++++ b/c/engine_internal.h +@@ -48,6 +48,8 @@ struct LiteRtLmStreamChunk { + const char* text = nullptr; + bool is_final = false; + const char* error_msg = nullptr; ++ // litert-lm-native finish-reason wire value; 0 when not reported. ++ int finish_reason = 0; + }; + + struct LiteRtLmRepetitionPenaltyConfig { +diff --git a/runtime/conversation/conversation.cc b/runtime/conversation/conversation.cc +index 4dcd8e15..9ae967e2 100644 +--- a/runtime/conversation/conversation.cc ++++ b/runtime/conversation/conversation.cc +@@ -755,6 +755,7 @@ absl::Status Conversation::SendMessageAsync( + const Message& message, + absl::AnyInvocable)> user_callback, + OptionalArgs optional_args) { ++ last_decode_stop_reason_.store(DecodeStopReason::kUnspecified); + if (!message.is_object()) { + return absl::InvalidArgumentError("Message must be a JSON object."); + } +@@ -968,13 +969,28 @@ absl::Status Conversation::SendMessageAsync( + + auto internal_callback = + std::make_shared)>>( +- CreateInternalCallback( +- *model_data_processor_, std::move(data_processor_args), +- config_.GetChannels(), std::move(wrapped_user_callback), +- remove_turn_from_history, std::move(complete_message_callback), +- open_channel_name, config_.return_error_on_max_tokens_reached(), +- config_.stream_tool_calls(), +- config_.stream_tool_calls_channel_name())); ++ [this, ++ callback = CreateInternalCallback( ++ *model_data_processor_, std::move(data_processor_args), ++ config_.GetChannels(), std::move(wrapped_user_callback), ++ remove_turn_from_history, std::move(complete_message_callback), ++ open_channel_name, config_.return_error_on_max_tokens_reached(), ++ config_.stream_tool_calls(), ++ config_.stream_tool_calls_channel_name())]( ++ absl::StatusOr responses) mutable { ++ if (responses.ok() && ++ IsTaskEndState(responses->GetTaskState())) { ++ DecodeStopReason reason = responses->GetDecodeStopReason(); ++ // A prefill can fill the context before any decode step. ++ if (reason == DecodeStopReason::kUnspecified && ++ responses->GetTaskState() == ++ TaskState::kMaxNumTokensReached) { ++ reason = DecodeStopReason::kMaxNumTokens; ++ } ++ last_decode_stop_reason_.store(reason); ++ } ++ callback(std::move(responses)); ++ }); + + if (session_inputs.empty()) { + auto decode_task_controller = session_->RunDecodeAsync( +diff --git a/runtime/conversation/conversation.h b/runtime/conversation/conversation.h +index 986fa1a6..622a7fa9 100644 +--- a/runtime/conversation/conversation.h ++++ b/runtime/conversation/conversation.h +@@ -15,6 +15,7 @@ + #ifndef THIRD_PARTY_ODML_LITERT_LM_RUNTIME_CONVERSATION_CONVERSATION_H_ + #define THIRD_PARTY_ODML_LITERT_LM_RUNTIME_CONVERSATION_CONVERSATION_H_ + ++#include + #include + #include + #include +@@ -655,6 +656,12 @@ class Conversation { + // non-callback thread) to observe the settled token count. + absl::StatusOr GetTokenCount() const; + ++ // Returns why the latest SendMessageAsync decode stopped. It is set before ++ // the final user callback and reset when the next message is sent. ++ DecodeStopReason GetLastDecodeStopReason() const { ++ return last_decode_stop_reason_.load(); ++ } ++ + // Returns the number of tokens the given messages would consume if added + // to the conversation, including template tokens and media (vision/audio) + // soft tokens. This does not mutate the conversation or the KV cache. +@@ -857,6 +864,9 @@ class Conversation { + // Whether the current conversation is in message appending state. + bool is_appending_message_ ABSL_GUARDED_BY(history_mutex_) = false; + ++ std::atomic last_decode_stop_reason_{ ++ DecodeStopReason::kUnspecified}; ++ + // Mutex for task_controllers_. + mutable absl::Mutex task_controllers_mutex_; + // Map of task group id to task controllers. +diff --git a/runtime/core/tasks.cc b/runtime/core/tasks.cc +index bd7a1c0c..5ca67a48 100644 +--- a/runtime/core/tasks.cc ++++ b/runtime/core/tasks.cc +@@ -136,28 +136,30 @@ absl::StatusOr> GetLogitsAsFloats( + return logits_data; + } + +-// Check whether the decoding loop should stop. +-bool ShouldStop(bool hit_stop_tokens, int benchmark_decode_token_count, +- int num_decoded_steps, int current_step, int max_num_tokens, +- int max_output_tokens) { ++// Check whether the decoding loop should stop, and why. ++// Returns kUnspecified when decoding should continue. ++DecodeStopReason ShouldStop(bool hit_stop_tokens, ++ int benchmark_decode_token_count, ++ int num_decoded_steps, int current_step, ++ int max_num_tokens, int max_output_tokens) { + // Stopping conditions. + if (hit_stop_tokens && benchmark_decode_token_count == 0) { + // Only early stop if no decode step + // is requested by benchmark. +- return true; ++ return DecodeStopReason::kStopToken; + } else if (benchmark_decode_token_count > 0 && + num_decoded_steps >= benchmark_decode_token_count) { + // Stop when the number of decode steps is equal to the + // benchmark_decode_token_count (when specified). +- return true; ++ return DecodeStopReason::kMaxOutputTokens; + } else if (current_step >= max_num_tokens) { + // Reaching maximum number of kv-cache size. +- return true; ++ return DecodeStopReason::kMaxNumTokens; + } else if (num_decoded_steps >= max_output_tokens) { + // Reaching maximum number of output tokens. +- return true; ++ return DecodeStopReason::kMaxOutputTokens; + } +- return false; ++ return DecodeStopReason::kUnspecified; + } + + // A helper class to filter the token stream based on stop tokens. +@@ -857,6 +859,7 @@ absl::StatusOr Decode( + std::move(no_repeat_ngram_config), std::move(suppress_tokens_config), + constraint, cancelled, speculative_decoding_config, + std::vector(draft_token_ids.begin(), draft_token_ids.end()))); ++ DecodeStopReason stop_reason = DecodeStopReason::kUnspecified; + while (true) { + if (cancelled != nullptr && cancelled->load()) { + if (benchmark_info.has_value()) { +@@ -943,8 +946,10 @@ absl::StatusOr Decode( + + ABSL_ASSIGN_OR_RETURN(int current_step, executor.GetCurrentStep()); + int num_decode_steps = current_step - executor_step_before_decode; +- if (ShouldStop(*all_done, benchmark_decode_token_count, num_decode_steps, +- current_step, max_num_tokens, max_output_tokens)) { ++ stop_reason = ++ ShouldStop(*all_done, benchmark_decode_token_count, num_decode_steps, ++ current_step, max_num_tokens, max_output_tokens); ++ if (stop_reason != DecodeStopReason::kUnspecified) { + break; + } + } +@@ -998,10 +1003,11 @@ absl::StatusOr Decode( + } + + if (is_streaming) { +- if (executor.GetCurrentStep().value() >= max_num_tokens) { +- return Responses(TaskState::kMaxNumTokensReached); +- } +- return Responses(TaskState::kDone); ++ Responses responses(executor.GetCurrentStep().value() >= max_num_tokens ++ ? TaskState::kMaxNumTokensReached ++ : TaskState::kDone); ++ responses.SetDecodeStopReason(stop_reason); ++ return responses; + } + + // Finalize scores for non-streaming custom sampling. +@@ -1017,9 +1023,11 @@ absl::StatusOr Decode( + TaskState task_state = executor.GetCurrentStep().value() >= max_num_tokens + ? TaskState::kMaxNumTokensReached + : TaskState::kDone; +- return Responses(std::move(task_state), std::move(final_texts), +- std::move(final_scores), /*token_lengths=*/{}, +- std::move(final_token_ids)); ++ Responses responses(std::move(task_state), std::move(final_texts), ++ std::move(final_scores), /*token_lengths=*/{}, ++ std::move(final_token_ids)); ++ responses.SetDecodeStopReason(stop_reason); ++ return responses; + } + + absl::StatusOr Score( +diff --git a/runtime/engine/io_types.h b/runtime/engine/io_types.h +index 2bd5649c..47cdecf5 100644 +--- a/runtime/engine/io_types.h ++++ b/runtime/engine/io_types.h +@@ -89,6 +89,14 @@ enum class TaskState { + }; + std::ostream& operator<<(std::ostream& os, const TaskState& task_state); + ++// Why a decode loop stopped, in upstream ShouldStop precedence order. ++enum class DecodeStopReason { ++ kUnspecified, // Not a finished decode. ++ kStopToken, // A stop token or stop sequence was decoded. ++ kMaxOutputTokens, // The output-token budget was reached. ++ kMaxNumTokens, // The KV cache (context window) is full. ++}; ++ + bool IsTaskEndState(const TaskState& task_state); + + // A container to host the model responses. +@@ -114,6 +122,11 @@ class Responses { + // Sets the task state. + void SetTaskState(TaskState task_state) { task_state_ = task_state; } + ++ DecodeStopReason GetDecodeStopReason() const { return decode_stop_reason_; } ++ void SetDecodeStopReason(DecodeStopReason reason) { ++ decode_stop_reason_ = reason; ++ } ++ + // Returns the const texts vector. + // The returned vector contains the response texts for each candidate output + // string. In most cases, the candidate number is 1, the vector will contain a +@@ -166,5 +179,7 @@ class Responses { + // The state of the task. + TaskState task_state_; + ++ DecodeStopReason decode_stop_reason_ = DecodeStopReason::kUnspecified; ++ + // The output vector of response tokens (as strings). + std::vector response_texts_; diff --git a/tests/huggingface_token_bytes/grammar_runtime_test.cc b/tests/huggingface_token_bytes/grammar_runtime_test.cc index 0b3e08f..a2145f2 100644 --- a/tests/huggingface_token_bytes/grammar_runtime_test.cc +++ b/tests/huggingface_token_bytes/grammar_runtime_test.cc @@ -80,7 +80,11 @@ int main(int argc, char** argv) { } Check(eos && space && null_id && true_id && false_id, "supported vocabulary controls"); litert::lm::LlGuidanceConfig config; +#ifdef LITERT_LM_LLGUIDANCE_V2 + config.eos_ids = {eos}; +#else config.eos_id = eos; +#endif auto provider = litert::lm::LlgConstraintProvider::Create(*tokenizer, config); Check(provider.ok(), "actual provider creation"); auto New = [&](const std::string& schema) { diff --git a/tests/huggingface_token_bytes/shim/llguidance.h b/tests/huggingface_token_bytes/shim/llguidance.h index e338b87..a8b7cab 100644 --- a/tests/huggingface_token_bytes/shim/llguidance.h +++ b/tests/huggingface_token_bytes/shim/llguidance.h @@ -33,6 +33,27 @@ inline LlgTokenizer* llg_new_tokenizer(const LlgTokenizerInit* init, char*, } return new LlgTokenizer; } +struct LlgTokenizerInitV2 { + size_t struct_size; + uint32_t vocab_size; + uint32_t tok_eos; + const uint32_t* token_lens; + const uint8_t* token_bytes; + bool tokenize_assumes_string; + size_t (*tokenize_fn)(const void*, const uint8_t*, size_t, uint32_t*, size_t); + const void* tokenize_user_data; + const uint32_t* tok_eos_extra; + uint32_t tok_eos_extra_count; + bool use_approximate_greedy_tokenize_fn = false; +}; +inline LlgTokenizer* llg_new_tokenizer_v2(const LlgTokenizerInitV2* init, + char* error, size_t size) { + const LlgTokenizerInit legacy{init->vocab_size, init->tok_eos, + init->token_lens, init->token_bytes, + init->tokenize_assumes_string, init->tokenize_fn, + init->tokenize_user_data}; + return llg_new_tokenizer(&legacy, error, size); +} inline void llg_free_tokenizer(LlgTokenizer* tokenizer) { delete tokenizer; } inline std::string captured_constraint; inline std::string captured_constraint_kind; diff --git a/tests/huggingface_token_bytes/shim/runtime/components/constrained_decoding/llg_constraint.h b/tests/huggingface_token_bytes/shim/runtime/components/constrained_decoding/llg_constraint.h index 5ed74b7..d59a798 100644 --- a/tests/huggingface_token_bytes/shim/runtime/components/constrained_decoding/llg_constraint.h +++ b/tests/huggingface_token_bytes/shim/runtime/components/constrained_decoding/llg_constraint.h @@ -8,5 +8,8 @@ class LlgConstraint : public Constraint { LlgConstraint(::LlgConstraint* value, int, int) { captured_created_constraint = value; } + LlgConstraint(::LlgConstraint* value, int, const std::vector&) { + captured_created_constraint = value; + } }; } // namespace litert::lm diff --git a/tests/huggingface_token_bytes/tokenizer_source_test.cc b/tests/huggingface_token_bytes/tokenizer_source_test.cc index e195abd..b158ae8 100644 --- a/tests/huggingface_token_bytes/tokenizer_source_test.cc +++ b/tests/huggingface_token_bytes/tokenizer_source_test.cc @@ -41,12 +41,12 @@ void* tokenizers_new_from_str(const char* data, size_t size) { } void tokenizers_free(void* data) { delete static_cast(data); } void tokenizers_encode(void*, const char*, size_t, int, - TokenizerEncodeResult*) { - std::abort(); -} -void tokenizers_free_encode_results(TokenizerEncodeResult*, size_t) { - std::abort(); + TokenizerEncodeResult* result) { + // This seam provides a vocabulary without a tokenizer for the text probes. + static uint32_t unused = 0; + *result = {&unused, 0}; } +void tokenizers_free_encode_results(TokenizerEncodeResult*, size_t) {} void tokenizers_token_to_id(void*, const char*, size_t, int32_t*) { std::abort(); } @@ -93,7 +93,11 @@ int main(int argc, char** argv) { "actual HF special ID"); } litert::lm::LlGuidanceConfig llg_config; +#ifdef LITERT_LM_LLGUIDANCE_V2 + llg_config.eos_ids = {0, 1}; +#else llg_config.eos_id = 0; +#endif llg_config.special_tokens = {raw.at(0)}; auto provider = litert::lm::LlgConstraintProvider::Create(*tokenizer, llg_config); @@ -103,7 +107,10 @@ int main(int argc, char** argv) { Check(captured_llg_tokens.size() == bytes->size(), "provider preserves IDs"); for (size_t id = 0; id < bytes->size(); ++id) { - const bool special = tokenizer->IsSpecialToken(id) || raw[id] == raw[0]; + bool special = tokenizer->IsSpecialToken(id) || raw[id] == raw[0]; +#ifdef LITERT_LM_LLGUIDANCE_V2 + special = special || id == 1; +#endif const std::string expected = special ? std::string(1, '\xFF') + raw[id] : bytes->at(id); Check(captured_llg_tokens[id] == expected, diff --git a/tools/android_gpu_safety_patch.py b/tools/android_gpu_safety_patch.py index 9f9119a..a35deb5 100644 --- a/tools/android_gpu_safety_patch.py +++ b/tools/android_gpu_safety_patch.py @@ -6,13 +6,34 @@ PATCH_PATH = "native/bridge/android_gpu_safety_v019.patch" # v0.19.1 leaves c/engine.cc and c/BUILD byte-identical to v0.19.0. -AUDITED_TAGS = frozenset({"v0.19.0", "v0.19.1"}) +AUDITED_TAGS = frozenset({"v0.19.0", "v0.19.1", "v0.20.0"}) SOURCES = {'c/engine.cc': ('d2cefd0a04312b5808daddf730a924e8b83e2b1cc6214a5a12e8b454d56557c2', '9ad52a303234df359a5a47256c512823b691c6c0c656b9a388bd544edda320e7'), 'c/BUILD': ('f72d6fc3e341497cc9cc5b8ba405b81d8aff1e9eed080cc5e4f281832e066748', '6a653c953a0389e44c5cddce60911ee9e148ade08b1b5a087b7657adeeb54d7d')} +V020_PATCH_PATH = "native/bridge/android_gpu_safety_v020.patch" +V020_SOURCES = { + "c/BUILD": ( + "cdd78f10cbc226bd45602f868dc07ae44bb9ed9ca1c9bf1c965fa9d47c6b34fe", + "78699dba1264eb02210c370d5741bcc8ab949cc368e3a3176be32a8feba41efb", + ), + "c/engine.cc": ( + "7db7cd3001f6060efa7f8c1b8e712098067ba99ed0921b0cb7cb543810599ad5", + "ff7f6fa7bb692c4bf5cc90c8a5c1f1f10aef74a92a33244a971ad02faf9d540e", + ), +} + + +def sources_for(tag: str) -> dict[str, tuple[str, str]]: + return V020_SOURCES if tag == "v0.20.0" else SOURCES + + +def patch_path_for(tag: str) -> str: + return V020_PATCH_PATH if tag == "v0.20.0" else PATCH_PATH + + def applies(tag: str) -> bool: if tag in AUDITED_TAGS: return True @@ -29,23 +50,23 @@ def digest(path: Path) -> str: def apply(source_root: Path, tag: str) -> None: if not applies(tag): return - observed = {name: digest(source_root / name) for name in SOURCES} - if all(observed[name] == post for name, (_, post) in SOURCES.items()): + observed = {name: digest(source_root / name) for name in sources_for(tag)} + if all(observed[name] == post for name, (_, post) in sources_for(tag).items()): return - if any(observed[name] != pre for name, (pre, _) in SOURCES.items()): + if any(observed[name] != pre for name, (pre, _) in sources_for(tag).items()): raise RuntimeError("C API safety source changed; requalify Android GPU preflight") - patch = Path(__file__).resolve().parents[1] / PATCH_PATH + patch = Path(__file__).resolve().parents[1] / patch_path_for(tag) subprocess.run(["git", "apply", "--check", str(patch)], cwd=source_root, check=True) subprocess.run(["git", "apply", str(patch)], cwd=source_root, check=True) - if any(digest(source_root / name) != post for name, (_, post) in SOURCES.items()): + if any(digest(source_root / name) != post for name, (_, post) in sources_for(tag).items()): raise RuntimeError("Android GPU preflight postimage mismatch") def manifest(tag: str) -> list[dict]: if not applies(tag): return [] - sha = hashlib.sha256((Path(__file__).resolve().parents[1] / PATCH_PATH).read_bytes()).hexdigest() - return [{"id": "android-qwen3-gpu-safety", "path": PATCH_PATH, "sha256": sha, + sha = hashlib.sha256((Path(__file__).resolve().parents[1] / patch_path_for(tag)).read_bytes()).hexdigest() + return [{"id": "android-qwen3-gpu-safety", "path": patch_path_for(tag), "sha256": sha, "source": name, "preimageSha256Lf": pre, "postimageSha256Lf": post, "scope": "source-built runtimes only; Android C API guard; excludes official upstream prebuilts"} - for name, (pre, post) in SOURCES.items()] + for name, (pre, post) in sources_for(tag).items()] diff --git a/tools/asr_litertlm_container_patch.py b/tools/asr_litertlm_container_patch.py index eb54ae7..4da9bf1 100644 --- a/tools/asr_litertlm_container_patch.py +++ b/tools/asr_litertlm_container_patch.py @@ -7,7 +7,7 @@ # v0.19.0 contains UPSTREAM_FIX_COMMIT and replaces AsrEngine with Omni session # factories, which load the ASR section and tokenizer from the container; # v0.19.1 keeps that source. -UPSTREAM_FIX_TAGS = frozenset({"v0.19.0", "v0.19.1"}) +UPSTREAM_FIX_TAGS = frozenset({"v0.19.0", "v0.19.1", "v0.20.0"}) PATCH_PATH = "native/bridge/asr_litertlm_container.patch" # Upstream google-ai-edge/LiteRT-LM bfdec21732 ("Support ASR models in # .litertlm") landed on main after the v0.18 release branch was cut. diff --git a/tools/asr_overlap_patch.py b/tools/asr_overlap_patch.py index 2b6e831..f6aa8e3 100644 --- a/tools/asr_overlap_patch.py +++ b/tools/asr_overlap_patch.py @@ -28,14 +28,21 @@ V019_MERGER_SOURCE = "omni/speech2text/timestamp_text_merger.cc" V019_OVERLAP_TAGS = frozenset({"v0.19.0", "v0.19.1"}) +V020_OVERLAP_TAG = "v0.20.0" +V020_PREIMAGE_SHA256 = "f6091439b29114fdb6cb010480e9b9b3961cd7c868925dc08f458f822ddecd65" +V020_POSTIMAGE_SHA256 = "4a7949344fb79d7c7e7c6fc4261b74031b1244f6bb83f741229483775efdd835" +OVERLAP_TAGS = AUDITED_OVERLAP_TAGS | V019_OVERLAP_TAGS | {V020_OVERLAP_TAG} + def merger_source(compatibility_tag: str) -> str: - return (V019_MERGER_SOURCE if compatibility_tag in V019_OVERLAP_TAGS + return (V019_MERGER_SOURCE if compatibility_tag in V019_OVERLAP_TAGS | {V020_OVERLAP_TAG} else MERGER_SOURCE) def overlap_identity(compatibility_tag: str) -> tuple[str, str, str]: """Returns the patch path, preimage and postimage for an audited tag.""" + if compatibility_tag == V020_OVERLAP_TAG: + return V019_PATCH_PATH, V020_PREIMAGE_SHA256, V020_POSTIMAGE_SHA256 if compatibility_tag in V019_OVERLAP_TAGS: return V019_PATCH_PATH, V019_PREIMAGE_SHA256, V019_POSTIMAGE_SHA256 return PATCH_PATH, PREIMAGE_SHA256, POSTIMAGE_SHA256 @@ -55,7 +62,7 @@ def require_asr_patch_decision(compatibility_tag: str) -> None: version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", compatibility_tag) if version and tuple(map(int, version.groups())) < (0, 18, 0): return - if compatibility_tag in AUDITED_OVERLAP_TAGS | V019_OVERLAP_TAGS: + if compatibility_tag in OVERLAP_TAGS: return raise RuntimeError( f"ASR untimed overlap has no explicit decision for {compatibility_tag}; " @@ -66,7 +73,7 @@ def require_asr_patch_decision(compatibility_tag: str) -> None: def source_patch_manifest(compatibility_tag: str) -> list[dict]: require_asr_patch_decision(compatibility_tag) - carried = compatibility_tag in AUDITED_OVERLAP_TAGS | V019_OVERLAP_TAGS + carried = compatibility_tag in OVERLAP_TAGS patch_path, preimage, postimage = overlap_identity(compatibility_tag) overlap = [] if not carried else [{ "id": "asr-untimed-overlap", diff --git a/tools/build_upstream_runtime.py b/tools/build_upstream_runtime.py index a33818c..d9a08eb 100644 --- a/tools/build_upstream_runtime.py +++ b/tools/build_upstream_runtime.py @@ -14,7 +14,7 @@ from android_protobuf_policy import validate_android_protobuf_isolation from android_gpu_safety_patch import apply as apply_android_gpu_safety from asr_litertlm_container_patch import SOURCES as CONTAINER_PATCH_SOURCES, require_container_patch_decision -from asr_overlap_patch import AUDITED_OVERLAP_TAGS, V019_OVERLAP_TAGS, merger_source, overlap_identity, source_sha256, require_asr_patch_decision +from asr_overlap_patch import OVERLAP_TAGS, merger_source, overlap_identity, source_sha256, require_asr_patch_decision from bazel_repository_provenance import release_workspace_rc, verify_resolved_archives from ios_runtime_policy import FST_DEFINE, provider_free_ios, validate_ios_directory, verify_upstream_fst_gate from download_utils import download_to_path @@ -41,10 +41,7 @@ uses_stream_chunk_api, ) from litert_stage_spatial_tensors_patch import ( - LITERT_ARCHIVE_SHA256 as STAGE_SPATIAL_TENSORS_LITERT_ARCHIVE_SHA256, - LITERT_REF as STAGE_SPATIAL_TENSORS_LITERT_REF, - PATCH_PATH as STAGE_SPATIAL_TENSORS_PATCH_PATH, - SOURCES as STAGE_SPATIAL_TENSORS_SOURCES, + identity_for as stage_spatial_tensors_identity, require_stage_spatial_tensors_patch_decision, ) from macos_runtime_identity import normalize_macos_runtime_identity @@ -199,7 +196,7 @@ def uses_shared_desktop_litert(platform: str, upstream_tag: str) -> bool: def patch_asr_untimed_overlap(source_root: Path, upstream_tag: str) -> None: """Carry #673 only on an audited source; require review on drift.""" require_asr_patch_decision(upstream_tag) - if upstream_tag not in AUDITED_OVERLAP_TAGS | V019_OVERLAP_TAGS: + if upstream_tag not in OVERLAP_TAGS: return patch_path, preimage, postimage = overlap_identity(upstream_tag) source = source_root / merger_source(upstream_tag) @@ -322,10 +319,12 @@ def verify_cpu_options_identifier_postimage(source_root: Path) -> None: print("Verified LiteRT CPU options identifier postimage", flush=True) -def verify_stage_spatial_tensors_postimages(source_root: Path) -> None: +def verify_stage_spatial_tensors_postimages( + source_root: Path, compatibility_tag: str = "v0.19.1" +) -> None: """Fails unless Bazel used the audited LiteRT WebGPU and Vulkan sources.""" repository = (source_root / "bazel-out").resolve().parents[2] / "external" / "litert" - for name, (_, postimage) in STAGE_SPATIAL_TENSORS_SOURCES.items(): + for name, (_, postimage) in stage_spatial_tensors_identity(compatibility_tag)[3].items(): source = repository / name if not source.is_file() or source_sha256(source.read_bytes()) != postimage: raise RuntimeError(f"LiteRT spatial tensor staging postimage mismatch for {name}; requalify") @@ -380,6 +379,7 @@ def download_upstream( patch_upstream_workspace( source_root, patch_ios_framework_paths=has_asr_bridge(compatibility_tag), + compatibility_tag=compatibility_tag, # v0.19.0 carries an equivalent SentencePiece patch of its own. patch_bpe_null_piece=is_at_least(compatibility_tag, (0, 17, 0)) and not is_at_least(compatibility_tag, (0, 19, 0)), @@ -449,9 +449,9 @@ def verify_carried_dependency_pins( return workspace = (source_root / "WORKSPACE").read_text(encoding="utf-8") if spatial_staging: + _, litert_ref, archive_sha256, _ = stage_spatial_tensors_identity(compatibility_tag) verify_litert_archive_pin( - workspace, STAGE_SPATIAL_TENSORS_LITERT_REF, - STAGE_SPATIAL_TENSORS_LITERT_ARCHIVE_SHA256, "LiteRT spatial tensor staging", + workspace, litert_ref, archive_sha256, "LiteRT spatial tensor staging", ) if cpu_options: verify_litert_archive_pin( @@ -471,6 +471,7 @@ def patch_upstream_workspace( patch_xnnpack_pf32_sme2: bool = False, patch_cpu_options_identifier: bool = False, patch_stage_spatial_tensors: bool = False, + compatibility_tag: str = "v0.19.1", ) -> None: workspace = source_root / "WORKSPACE" text = workspace.read_text(encoding="utf-8") @@ -491,17 +492,19 @@ def patch_upstream_workspace( text = text.replace(needle, replacement) litert_patches = [] if patch_ios_framework_paths: - litert_patches.append("litert_ios_framework_paths.patch") + litert_patches.append("litert_ios_framework_paths_v020.patch" + if compatibility_tag == "v0.20.0" + else "litert_ios_framework_paths.patch") if patch_gpu_environment_teardown: litert_patches.append("litert_gpu_environment_destroy_callback.patch") if patch_cpu_options_identifier: litert_patches.append("litert_cpu_options_identifier.patch") if patch_stage_spatial_tensors: + patch_path, litert_ref, archive_sha256, _ = stage_spatial_tensors_identity(compatibility_tag) verify_litert_archive_pin( - text, STAGE_SPATIAL_TENSORS_LITERT_REF, - STAGE_SPATIAL_TENSORS_LITERT_ARCHIVE_SHA256, "LiteRT spatial tensor staging", + text, litert_ref, archive_sha256, "LiteRT spatial tensor staging", ) - litert_patches.append(Path(STAGE_SPATIAL_TENSORS_PATCH_PATH).name) + litert_patches.append(Path(patch_path).name) litert_archive = 'http_archive(\n name = "litert",\n' litert_archive_with_patch = ( litert_archive @@ -705,7 +708,10 @@ def build_runtime( command.append("--define=litert_lm_c_api_v1=true") if in_process_litert_abi_version(upstream_tag) == 1: command.append("--define=litert_lm_in_process_litert=true") - if platform == "android" and not has_prebuilt_topk_samplers(upstream_tag): + if platform == "android" and is_at_least(upstream_tag, (0, 20, 0)): + command.extend(("--//runtime/executor:gpu_accelerator=webgpu", + "--define=litert_lm_android_opencl_sampler=true")) + elif platform == "android" and not has_prebuilt_topk_samplers(upstream_tag): command.append("--define=litert_lm_android_webgpu_sampler=true") if require_finish_reason_patch_decision(upstream_tag): command.append(FINISH_REASON_DEFINE) @@ -720,10 +726,8 @@ def build_runtime( command.append(f"--jobs={jobs}") pins = {} if patch_stage_spatial_tensors: - pins["litert"] = ( - STAGE_SPATIAL_TENSORS_LITERT_ARCHIVE_SHA256, - f"LiteRT-{STAGE_SPATIAL_TENSORS_LITERT_REF}", - ) + _, litert_ref, archive_sha256, _ = stage_spatial_tensors_identity(upstream_tag) + pins["litert"] = (archive_sha256, f"LiteRT-{litert_ref}") if patch_cpu_options_identifier: pins["litert"] = (CPU_OPTIONS_LITERT_ARCHIVE_SHA256, f"LiteRT-{CPU_OPTIONS_LITERT_REF}") if patch_xnnpack: @@ -747,7 +751,7 @@ def build_runtime( if patch_cpu_options_identifier: verify_cpu_options_identifier_postimage(source_root) if patch_stage_spatial_tensors: - verify_stage_spatial_tensors_postimages(source_root) + verify_stage_spatial_tensors_postimages(source_root, upstream_tag) if "output" in target: output = source_root / target["output"] diff --git a/tools/huggingface_token_bytes_patch.py b/tools/huggingface_token_bytes_patch.py index c74e37b..f732e95 100644 --- a/tools/huggingface_token_bytes_patch.py +++ b/tools/huggingface_token_bytes_patch.py @@ -5,7 +5,7 @@ from pathlib import Path PATCH_PATH = "native/bridge/huggingface_token_bytes_v019.patch" -AUDITED_TAGS = frozenset({"v0.19.0", "v0.19.1"}) +AUDITED_TAGS = frozenset({"v0.19.0", "v0.19.1", "v0.20.0"}) # LF-normalized upstream v0.19.0 / 83ce6067 preimages and patched postimages; # v0.19.1 / 7a03724c leaves every preimage unchanged. SOURCES = { @@ -36,6 +36,43 @@ } +V020_PATCH_PATH = "native/bridge/huggingface_token_bytes_v020.patch" +V020_SOURCES = { + "runtime/components/constrained_decoding/BUILD": ( + "dfce389070058c835975ca2f76d4858830156928b12131c53a5933cb522661f8", + "a73f1ba0602ed08e6b6c63042be557fed3a6d1815d92cf588d96a8d14cde4b6b", + ), + "runtime/components/constrained_decoding/llg_constraint_provider.cc": ( + "793ec01ba12f7b0a4ae6d5ba75ab226ec064d5aaff3fdde7698115f927ca3122", + "722aaa0e0204e74ecf56bbd9675d59be3b6537d944074236606c279421a69e2d", + ), + "support/tokenizer/BUILD": ( + "8d7f0fb096e24f468057dd4a4d276962e898693857dedb0743805be388117610", + "117ab89ab377a2067b34f8ea84a9fdc2d054d0b3303a49c85f24ff3542660c01", + ), + "support/tokenizer/huggingface_tokenizer.cc": ( + "ec69b3dff009ede39d82c1d280d859530cc3cc598b36a9c8cc94d986adf24c20", + "5853d97e37a62957331db217c9f5e4a2f5ef89e725f5417aac350232505edad6", + ), + "support/tokenizer/huggingface_tokenizer.h": ( + "b9c723c1314869d347a119378a978612f48ac6575317ca0aad41a3dabbacf74a", + "5623e1a7fe0e8723fca39c7902dd2b7a8b5f4f846a7e53b88b078e8c36a5d7cd", + ), + "support/tokenizer/tokenizer.h": ( + "f80f9685c276c303bb3110203069ece92bcc61276db537baee50599eed2ad1da", + "b0ca05aa33fc0a6d7b735806383970e2f24e52d55db6c2bb8192b7123a20ae44", + ), +} + + +def sources_for(tag: str) -> dict[str, tuple[str, str]]: + return V020_SOURCES if tag == "v0.20.0" else SOURCES + + +def patch_path_for(tag: str) -> str: + return V020_PATCH_PATH if tag == "v0.20.0" else PATCH_PATH + + def require_token_bytes_patch_decision(tag: str) -> bool: version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", tag) if version and tuple(map(int, version.groups())) < (0, 19, 0): @@ -53,16 +90,16 @@ def _digest(path: Path) -> str: def apply(source_root: Path, tag: str) -> None: if not require_token_bytes_patch_decision(tag): return - digests = {name: _digest(source_root / name) for name in SOURCES} - if all(digests[name] == post for name, (_, post) in SOURCES.items()): + digests = {name: _digest(source_root / name) for name in sources_for(tag)} + if all(digests[name] == post for name, (_, post) in sources_for(tag).items()): return - if any(digests[name] != pre for name, (pre, _) in SOURCES.items()): + if any(digests[name] != pre for name, (pre, _) in sources_for(tag).items()): raise RuntimeError("Tokenizer or grammar source changed; requalify #100 token bytes patch") - patch = Path(__file__).resolve().parents[1] / PATCH_PATH + patch = Path(__file__).resolve().parents[1] / patch_path_for(tag) command = ["git", "apply", "--ignore-space-change", str(patch)] subprocess.run([*command[:2], "--check", *command[2:]], check=True, cwd=source_root) subprocess.run(command, check=True, cwd=source_root) - if any(_digest(source_root / name) != post for name, (_, post) in SOURCES.items()): + if any(_digest(source_root / name) != post for name, (_, post) in sources_for(tag).items()): raise RuntimeError("HuggingFace token bytes postimage mismatch; requalify #100") @@ -70,9 +107,9 @@ def token_bytes_patch_manifest(tag: str) -> list[dict]: if not require_token_bytes_patch_decision(tag): return [] digest = hashlib.sha256( - (Path(__file__).resolve().parents[1] / PATCH_PATH).read_bytes()).hexdigest() + (Path(__file__).resolve().parents[1] / patch_path_for(tag)).read_bytes()).hexdigest() return [{ - "id": "huggingface-token-bytes", "path": PATCH_PATH, "sha256": digest, + "id": "huggingface-token-bytes", "path": patch_path_for(tag), "sha256": digest, "source": name, "preimageSha256Lf": pre, "postimageSha256Lf": post, "scope": "source-built runtimes only; excludes official upstream prebuilts", - } for name, (pre, post) in SOURCES.items()] + } for name, (pre, post) in sources_for(tag).items()] diff --git a/tools/litert_cpu_options_identifier_patch.py b/tools/litert_cpu_options_identifier_patch.py index 1eff11e..eb8090c 100644 --- a/tools/litert_cpu_options_identifier_patch.py +++ b/tools/litert_cpu_options_identifier_patch.py @@ -8,7 +8,7 @@ # v0.19.0 ships Linux and Windows prebuilt libLiteRt that read "cpu_options", # the same identifier its pinned LiteRT dcb657e8 writes. v0.19.1 keeps both the # LiteRT pin and those prebuilts. -UPSTREAM_FIX_TAGS = frozenset({"v0.19.0", "v0.19.1"}) +UPSTREAM_FIX_TAGS = frozenset({"v0.19.0", "v0.19.1", "v0.20.0"}) # LiteRT 724a247cc5 renamed the CPU options identifier from "xnnpack" to # "cpu_options". v0.18.1 pins LiteRT ca21dc99, which has the rename, but still # ships the 2026-09-28 prebuilt libLiteRt from before it. Linux and Windows diff --git a/tools/litert_lm_c_api.py b/tools/litert_lm_c_api.py index a01ac50..0135301 100644 --- a/tools/litert_lm_c_api.py +++ b/tools/litert_lm_c_api.py @@ -1,6 +1,6 @@ """ctypes access to the LiteRT-LM C API across its two calling conventions. -C API 1.0 (LiteRT-LM v0.19) returns a status code and writes results through +C API 1.x (LiteRT-LM v0.19 and later) returns a status code and writes results through trailing out parameters. Older runtimes return results directly. Tools call the wrappers here so one tool can qualify both, for example when comparing a candidate against a published baseline. diff --git a/tools/litert_lm_finish_reason_smoke.py b/tools/litert_lm_finish_reason_smoke.py index b23e967..81789b4 100644 --- a/tools/litert_lm_finish_reason_smoke.py +++ b/tools/litert_lm_finish_reason_smoke.py @@ -228,6 +228,11 @@ def main() -> int: expected = expected_abi_version(args.upstream_tag) print(f"stream_proxy_finish_reason_abi_version() = {version}; " f"{args.upstream_tag} expects {expected}") + if args.upstream_tag == "v0.20.0": + c_version = api.api_version() + print(f"LiteRT-LM C API version: {c_version}; expected (1, 1, 0)") + if c_version != (1, 1, 0): + return 1 in_process = in_process_litert_matches(library, args.upstream_tag) return 0 if version == expected and in_process else 1 if version != 1: diff --git a/tools/litert_lm_step_zero_smoke.py b/tools/litert_lm_step_zero_smoke.py index 49864e5..c314c06 100644 --- a/tools/litert_lm_step_zero_smoke.py +++ b/tools/litert_lm_step_zero_smoke.py @@ -39,8 +39,8 @@ def __init__(self, library: Path) -> None: self.api = CApi(library) self.library = self.api.library self.version = self.api.api_version() - if self.version[:2] != (1, 0): - raise RuntimeError(f"Expected C API 1.0, found {self.version}") + if self.version[:2] not in {(1, 0), (1, 1)} or self.version[2] < 0: + raise RuntimeError(f"Expected C API 1.0.x or 1.1.x, found {self.version}") self.api.set_min_log_level(0) for name, types in { "engine_settings_set_max_num_tokens": [ct.c_void_p, ct.c_int], diff --git a/tools/litert_stage_spatial_tensors_patch.py b/tools/litert_stage_spatial_tensors_patch.py index e8518df..38b36a6 100644 --- a/tools/litert_stage_spatial_tensors_patch.py +++ b/tools/litert_stage_spatial_tensors_patch.py @@ -26,9 +26,37 @@ ), } +V020_PATCH_PATH = "native/bridge/litert_stage_spatial_tensors_v020.patch" +V020_LITERT_REF = "bf49eb62406d15948261a840c9dcd8e4f13b478c" +V020_LITERT_ARCHIVE_SHA256 = "f5ee44f21843bc6634c02d20d5abb2e4dc0feb83d702b73b5073f10c008231ba" +V020_SOURCES = { + "ml_drift_delegate/delegate/gpu_backend_vulkan.cc": ( + "94510294e45a568440e87366facbae6294a1087a52bbbcbab05e5f6ceec6d3dd", + "ee5943a90770691b5e959152c02aaad642d9f6b42ddfbe08b1e3cb79bf8e614a", + ), + "ml_drift_delegate/delegate/gpu_backend_vulkan.h": ( + "5d7b59f6e1c03749333bd650911c1ffc0e911932d65b0762c87f5616574ceb0b", + "66eebf4c18828637fcbcdb360c2192a446c070e5519fd61936b782f2faa5363b", + ), + "ml_drift_delegate/delegate/gpu_backend_webgpu.cc": ( + "38906e7dd17317e946eff46e8b185505bf1f463043d19b24318b30d4e4089bb5", + "1d8ab8c31766429ee5e4423a62aa60dab6b09abcfb81f7672474d22b49978dad", + ), + "ml_drift_delegate/delegate/gpu_backend_webgpu.h": ( + "e6b0a47805e83db622ce65d6d8bb5535a03a867456e4bcb72ae16044ce23f041", + "9c795eedf6256288b1e7f33bff028d5af99e9958d6568dd40276d4bda46b06c3", + ), +} + + +def identity_for(compatibility_tag: str) -> tuple[str, str, str, dict[str, tuple[str, str]]]: + if compatibility_tag == "v0.20.0": + return V020_PATCH_PATH, V020_LITERT_REF, V020_LITERT_ARCHIVE_SHA256, V020_SOURCES + return PATCH_PATH, LITERT_REF, LITERT_ARCHIVE_SHA256, SOURCES + def require_stage_spatial_tensors_patch_decision(compatibility_tag: str) -> bool: - if compatibility_tag == "v0.19.1": + if compatibility_tag in {"v0.19.1", "v0.20.0"}: return True version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", compatibility_tag) if version and tuple(map(int, version.groups())) <= (0, 19, 0): @@ -42,16 +70,17 @@ def require_stage_spatial_tensors_patch_decision(compatibility_tag: str) -> bool def stage_spatial_tensors_patch_manifest(compatibility_tag: str) -> list[dict]: if not require_stage_spatial_tensors_patch_decision(compatibility_tag): return [] + patch_path, litert_ref, _, sources = identity_for(compatibility_tag) patch_sha256 = hashlib.sha256( - (Path(__file__).resolve().parents[1] / PATCH_PATH).read_bytes() + (Path(__file__).resolve().parents[1] / patch_path).read_bytes() ).hexdigest() return [{ "id": "litert-stage-spatial-tensors", - "path": PATCH_PATH, + "path": patch_path, "sha256": patch_sha256, - "source": f"LiteRT@{LITERT_REF}/{source}", + "source": f"LiteRT@{litert_ref}/{source}", "preimageSha256Lf": preimage, "postimageSha256Lf": postimage, "scope": ("source-built runtimes only; excludes official upstream prebuilts; " f"backports google-ai-edge/LiteRT@{UPSTREAM_FIX}"), - } for source, (preimage, postimage) in SOURCES.items()] + } for source, (preimage, postimage) in sources.items()] diff --git a/tools/prebuilt_overrides.py b/tools/prebuilt_overrides.py index 2274346..ef49207 100644 --- a/tools/prebuilt_overrides.py +++ b/tools/prebuilt_overrides.py @@ -102,6 +102,7 @@ def target_path(self) -> str: "v0.19.0": ANDROID_DAWN_ROLLBACKS, # v0.19.1 ships the same prebuilt Dawn and accelerator payloads as v0.19.0. "v0.19.1": ANDROID_DAWN_ROLLBACKS, + "v0.20.0": ANDROID_DAWN_ROLLBACKS, } diff --git a/tools/qualify_asr_untimed_overlap.py b/tools/qualify_asr_untimed_overlap.py index 76d8bbb..4f3c05e 100644 --- a/tools/qualify_asr_untimed_overlap.py +++ b/tools/qualify_asr_untimed_overlap.py @@ -51,15 +51,15 @@ def compiler_command(source: Path, work: Path) -> list[str]: @lru_cache(maxsize=None) -def compile_shared_objects(source: Path, work: Path) -> tuple[Path, Path]: +def compile_shared_objects(source: Path, work: Path, tag: str) -> tuple[Path, ...]: # Reuse only within this process, never stale objects from a previous run. # Every mutant still compiles its own actual merger implementation. outputs = [] - merger_dir = Path(merger_source(QUALIFIED_TAG)).parent + merger_dir = Path(merger_source(tag)).parent + text_utils = "omni/utils" if tag == "v0.20.0" else "omni/base" for name, unit in (("driver", REPO / "native/bridge/litert_lm_asr_merger_test.cc"), ("levenshtein", source / merger_dir / "levenshtein_align.cc"), - *([("text_utils", source / "omni/base/text_utils.cc")] - if (source / "omni/base/text_utils.cc").is_file() else [])): + ("text_utils", source / text_utils / "text_utils.cc")): output = work / (name + ".o") subprocess.run([*compiler_command(source, work), "-c", str(unit), "-o", str(output)], check=True) @@ -67,21 +67,21 @@ def compile_shared_objects(source: Path, work: Path) -> tuple[Path, Path]: return tuple(outputs) -def compile_driver(source: Path, work: Path, merger: Path, output: Path) -> None: - shared = compile_shared_objects(source, work) +def compile_driver(source: Path, work: Path, merger: Path, output: Path, tag: str) -> None: + shared = compile_shared_objects(source, work, tag) _, ldflags = abseil_flags() subprocess.run([*compiler_command(source, work), str(merger), *map(str, shared), *ldflags, "-o", str(output)], check=True) -def compile_replays(source: Path, work: Path) -> tuple[Path, Path]: +def compile_replays(source: Path, work: Path, tag: str) -> tuple[Path, Path]: work.mkdir(parents=True, exist_ok=True) patched = work / "patched" - merger = merger_source(QUALIFIED_TAG) + merger = merger_source(tag) target = patched / merger target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(source / merger, target) - patch_asr_untimed_overlap(patched, QUALIFIED_TAG) + patch_asr_untimed_overlap(patched, tag) # The merger uses only LiteRT's status macro. This alias avoids fetching # the full LiteRT dependency closure and preserves the same status behavior. shim = work / "litert/cc/litert_macros.h" @@ -91,7 +91,7 @@ def compile_replays(source: Path, work: Path) -> tuple[Path, Path]: outputs = [] for name, unit in (("upstream", source / merger), ("fixed", target)): output = work / name - compile_driver(source, work, unit, output) + compile_driver(source, work, unit, output, tag) outputs.append(output) subprocess.run([str(outputs[1])], check=True) return tuple(outputs) @@ -228,10 +228,10 @@ def check_clean_boundaries(upstream: Path, fixed: Path, cache: dict | None = Non def check_mutations(source: Path, work: Path, upstream: Path, fixed: Path, - clean_cache: dict, equivalence_count: int = 40) -> dict: + clean_cache: dict, equivalence_count: int, tag: str) -> dict: # Extends audit mut/mut.py. Mutations change the real merger source, then # compile and run the same native tests and negative differential controls. - text = (work / "patched" / merger_source(QUALIFIED_TAG)).read_text() + text = (work / "patched" / merger_source(tag)).read_text() mutations = { "M4_one_word": ("min_anchor_words = 2", "min_anchor_words = 1"), "M5_three_words": ("min_anchor_words = 2", "min_anchor_words = 3"), @@ -265,7 +265,7 @@ def check_mutations(source: Path, work: Path, upstream: Path, fixed: Path, mutant = work / (name + ".cc") mutant.write_text(variant) binary = work / name - compile_driver(source, work, mutant, binary) + compile_driver(source, work, mutant, binary, tag) native = subprocess.run([str(binary)], capture_output=True, text=True) negative = False try: @@ -307,13 +307,15 @@ def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source-root", type=Path, required=True) parser.add_argument("--work-dir", type=Path, required=True) + parser.add_argument("--upstream-tag", default=QUALIFIED_TAG) parser.add_argument("--mutations", action="store_true") parser.add_argument("--equivalence-count", type=int, default=40, help="Cases/seed for the equivalent tie mutation (400 for the full audit)") args = parser.parse_args() if args.equivalence_count < 1: parser.error("--equivalence-count must be positive") - upstream, fixed = compile_replays(args.source_root.resolve(), args.work_dir.resolve()) + upstream, fixed = compile_replays(args.source_root.resolve(), args.work_dir.resolve(), + args.upstream_tag) clean_cache = {} result = dict(abseil_pkg_versions=dict(zip(ABSL_PACKAGES, subprocess.check_output( ["pkg-config", "--modversion", *ABSL_PACKAGES], text=True).splitlines())), @@ -326,7 +328,7 @@ def main() -> None: if args.mutations: result["mutations"] = check_mutations(args.source_root.resolve(), args.work_dir.resolve(), upstream, fixed, clean_cache, - args.equivalence_count) + args.equivalence_count, args.upstream_tag) (args.work_dir / "results.json").write_text(json.dumps(result, indent=2) + "\n") print(json.dumps(result, indent=2)) diff --git a/tools/qualify_huggingface_token_bytes.py b/tools/qualify_huggingface_token_bytes.py index beb7a13..825b701 100644 --- a/tools/qualify_huggingface_token_bytes.py +++ b/tools/qualify_huggingface_token_bytes.py @@ -11,7 +11,7 @@ import shutil import subprocess -from huggingface_token_bytes_patch import SOURCES, apply as apply_token_bytes_patch +from huggingface_token_bytes_patch import apply as apply_token_bytes_patch, sources_for REPO = Path(__file__).resolve().parents[1] @@ -80,7 +80,7 @@ def mutation_controls(compiler: str, cflags: list[str], work_dir: Path) -> list[ def qualify(work_dir: Path, tokenizer_json: Path | None = None, source_root: Path | None = None, mutations: bool = False, *, - runtime_library: Path | None = None, + upstream_tag: str = "v0.19.0", runtime_library: Path | None = None, llguidance_include: Path | None = None, schema_json: Path | None = None, observed_output: Path | None = None) -> dict: @@ -129,13 +129,15 @@ def qualify(work_dir: Path, tokenizer_json: Path | None = None, patched = work_dir / "patched" headers = ["runtime/components/constrained_decoding/" + name for name in ("llg_constraint_provider.h", "llg_constraint_config.h", "constraint_provider.h")] - for name in [*SOURCES, *headers]: + for name in [*sources_for(upstream_tag), *headers]: target = patched / name target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(source_root / name, target) - apply_token_bytes_patch(patched, "v0.19.0") + apply_token_bytes_patch(patched, upstream_tag) source_binary = work_dir / "huggingface_tokenizer_source_test" packages = ["absl_statusor", "absl_leak_check", "absl_status_macros", "absl_flat_hash_set"] + if upstream_tag == "v0.20.0": + packages += ["absl_log", "absl_strings", "absl_synchronization"] flags = shlex.split(subprocess.check_output( ["pkg-config", "--cflags", "--libs", *packages], text=True)) source_command = [compiler, "-std=c++17", "-O2", "-Wall", "-Wextra", *cflags, @@ -145,6 +147,8 @@ def qualify(work_dir: Path, tokenizer_json: Path | None = None, str(patched / "runtime/components/constrained_decoding/llg_constraint_provider.cc"), str(REPO / "tests/huggingface_token_bytes/tokenizer_source_test.cc"), *flags, "-o", str(source_binary)] + if upstream_tag == "v0.20.0": + source_command.insert(1, "-DLITERT_LM_LLGUIDANCE_V2") subprocess.run(source_command, check=True, timeout=120) subprocess.run([str(source_binary.resolve()), *command[1:]], check=True, timeout=30) @@ -260,6 +264,7 @@ def main() -> None: parser.add_argument("--work-dir", type=Path, required=True) parser.add_argument("--tokenizer-json", type=Path) parser.add_argument("--source-root", type=Path) + parser.add_argument("--upstream-tag", default="v0.19.0") parser.add_argument("--mutations", action="store_true") parser.add_argument("--runtime-library", type=Path) parser.add_argument("--llguidance-include", type=Path) @@ -268,7 +273,7 @@ def main() -> None: args = parser.parse_args() print(json.dumps(qualify( args.work_dir, args.tokenizer_json, args.source_root, args.mutations, - runtime_library=args.runtime_library, llguidance_include=args.llguidance_include, + upstream_tag=args.upstream_tag, runtime_library=args.runtime_library, llguidance_include=args.llguidance_include, schema_json=args.schema_json, observed_output=args.observed_output), indent=2)) diff --git a/tools/runtime_dependency_utils.py b/tools/runtime_dependency_utils.py index d2ad477..63ff4b1 100644 --- a/tools/runtime_dependency_utils.py +++ b/tools/runtime_dependency_utils.py @@ -163,6 +163,14 @@ def elf_has_global_flag(path: Path) -> bool: def elf_exported_symbols(path: Path, *, include_hidden: bool = False) -> set[str]: + return _elf_dynamic_symbols(path, undefined=False, include_hidden=include_hidden) + + +def elf_imported_symbols(path: Path) -> set[str]: + return _elf_dynamic_symbols(path, undefined=True, include_hidden=False) + + +def _elf_dynamic_symbols(path: Path, *, undefined: bool, include_hidden: bool) -> set[str]: data = path.read_bytes() if len(data) < 64 or not data.startswith(ELF_MAGIC): return set() @@ -219,7 +227,7 @@ def elf_exported_symbols(path: Path, *, include_hidden: bool = False) -> set[str binding = info >> 4 if ( name_offset == 0 - or section_index == SHN_UNDEF + or (section_index == SHN_UNDEF) != undefined or binding not in (STB_GLOBAL, STB_WEAK, STB_GNU_UNIQUE) or (not include_hidden and (other & 3) not in (0, 3)) ): diff --git a/tools/step_zero_state_patch.py b/tools/step_zero_state_patch.py index 42bf793..69f52e4 100644 --- a/tools/step_zero_state_patch.py +++ b/tools/step_zero_state_patch.py @@ -8,11 +8,20 @@ SOURCE = "runtime/executor/llm_litert_compiled_model_executor.cc" PREIMAGE = "5e6898eb07178719c554ed49e4bc79d891badea4ad0576d00af54ef1bd8dbb4c" POSTIMAGE = "b2c73fbcb400654072bf926dbaa3b81e252acf750f8fc1a60dd0b51df84d890d" -PATCH = Path(__file__).resolve().parents[1] / PATCH_PATH + +V020_PATCH_PATH = "native/bridge/step_zero_state_v020.patch" +V020_PREIMAGE = "4ccb5ef331ab7d10927d618fee8041cf030500700646efeb2aab0e57c3212c32" +V020_POSTIMAGE = "96ebbe1e0cdbdcfe00407cf6ead2b2df1073ab9eb53695a917bf487da3482e7a" + + +def identity_for(tag: str) -> tuple[str, str, str]: + if tag == "v0.20.0": + return V020_PATCH_PATH, V020_PREIMAGE, V020_POSTIMAGE + return PATCH_PATH, PREIMAGE, POSTIMAGE def applies(tag: str) -> bool: - if tag == "v0.19.1": + if tag in {"v0.19.1", "v0.20.0"}: return True version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", tag) if version and tuple(map(int, version.groups())) < (0, 19, 1): @@ -28,28 +37,31 @@ def _digest(path: Path) -> str: def apply(source_root: Path, tag: str) -> None: if not applies(tag): return + patch_path, preimage, postimage = identity_for(tag) path = source_root / SOURCE digest = _digest(path) - if digest == POSTIMAGE: + if digest == postimage: return - if digest != PREIMAGE: + if digest != preimage: raise RuntimeError("Executor source changed; requalify the step-zero state patch") - args = ["--ignore-space-change", str(PATCH)] + args = ["--ignore-space-change", str(Path(__file__).resolve().parents[1] / patch_path)] subprocess.run(["git", "apply", "--check", *args], check=True, cwd=source_root) subprocess.run(["git", "apply", *args], check=True, cwd=source_root) - if _digest(path) != POSTIMAGE: + if _digest(path) != postimage: raise RuntimeError("Executor step-zero state postimage mismatch") def manifest(tag: str) -> list[dict]: if not applies(tag): return [] + patch_path, preimage, postimage = identity_for(tag) + patch = Path(__file__).resolve().parents[1] / patch_path return [{ "id": "step-zero-state", - "path": PATCH_PATH, - "sha256": hashlib.sha256(PATCH.read_bytes()).hexdigest(), + "path": patch_path, + "sha256": hashlib.sha256(patch.read_bytes()).hexdigest(), "source": SOURCE, - "preimageSha256Lf": PREIMAGE, - "postimageSha256Lf": POSTIMAGE, + "preimageSha256Lf": preimage, + "postimageSha256Lf": postimage, "scope": "source-built runtimes only; excludes official upstream prebuilts", }] diff --git a/tools/stream_finish_reason_patch.py b/tools/stream_finish_reason_patch.py index ea26e20..4d6e3f0 100644 --- a/tools/stream_finish_reason_patch.py +++ b/tools/stream_finish_reason_patch.py @@ -6,7 +6,7 @@ PATCH_PATH = "native/bridge/stream_finish_reason.patch" BAZEL_DEFINE = "--define=litert_lm_finish_reason_api=true" # v0.18.1 changes dependencies only; all six preimages equal v0.18.0. -AUDITED_FINISH_REASON_TAGS = frozenset({"v0.18.0", "v0.18.1", "v0.19.0", "v0.19.1"}) +AUDITED_FINISH_REASON_TAGS = frozenset({"v0.18.0", "v0.18.1", "v0.19.0", "v0.19.1", "v0.20.0"}) # LF-normalized (preimage, postimage) SHA-256 per patched v0.18.0 source. SOURCES = { "c/conversation.cc": ( @@ -68,11 +68,48 @@ } +V020_PATCH_PATH = "native/bridge/stream_finish_reason_v020.patch" +V020_SOURCES = { + "c/c_api_internal.h": ( + "bcd6bce2a4b986f2cac4ba8869fef944cd3ee2fa47f21f837a1ff5c5876c1504", + "546a4e509e368d2d0a3232df4f9c204d9c66beb9fe17fdca089e1ce5a545a777", + ), + "c/conversation.cc": ( + "518fe5457b36a020fe49b8370390ee47725afd083f457a7b92877fc55e98c246", + "ef6ea2b8ec99fdc04704e93dff71ae1d125b2c3269268fd502eb87f6f7fb06e1", + ), + "c/engine_internal.h": ( + "7955c97b6f1c02a8a7828c370d7ec869dc1f1e23b3fa030b1d075e4a6a495af7", + "e3663bc8be651228f40f6e23cd8ad088bb9975bf85dbc216abf55343157c1ff0", + ), + "runtime/conversation/conversation.cc": ( + "2c91850bcc70d953d45ff52084dd29a110a74bb5a83b142d73807c147b87579e", + "bcd284bc4738df7c2e360e1f14ca734962a4688ee2ea79ba493ef820b68ec15e", + ), + "runtime/conversation/conversation.h": ( + "3d3b936089c13142e65a195fee59ba2449734f5a338074eb9f9e5ccb419639cf", + "3c4280fe15bbebc003dd9b97bb4a78f9db52cd952afa34279f9826282a7383b3", + ), + "runtime/core/tasks.cc": ( + "3970f6f747fc39e05746c3e80d4cadc315be28b01cf4911ed05aee7f40df10df", + "38e068714f2995b86fb57121f2261369c471e1d5040a812f2531bacd96cb080a", + ), + "runtime/engine/io_types.h": ( + "99da02ec968a379099ca86e25ba5a0f91df820de1b58d9315c4c1215ac9474b3", + "2c7c79d5a0f8d6de47fb8c3220de3b8b37230f9c49f8f4772f93dfa3b79f2a89", + ), +} + + def patch_path_for(compatibility_tag: str) -> str: + if compatibility_tag == "v0.20.0": + return V020_PATCH_PATH return V019_PATCH_PATH if compatibility_tag in V019_TAGS else PATCH_PATH def sources_for(compatibility_tag: str) -> dict[str, tuple[str, str]]: + if compatibility_tag == "v0.20.0": + return V020_SOURCES return V019_SOURCES if compatibility_tag in V019_TAGS else SOURCES diff --git a/tools/test_android_gpu_safety.py b/tools/test_android_gpu_safety.py index f6431e0..b753f2b 100644 --- a/tools/test_android_gpu_safety.py +++ b/tools/test_android_gpu_safety.py @@ -6,7 +6,7 @@ import tempfile import unittest -from android_gpu_safety_patch import SOURCES, apply, applies, digest, manifest +from android_gpu_safety_patch import SOURCES, apply, applies, digest, manifest, sources_for ROOT = Path(__file__).resolve().parents[1] @@ -16,7 +16,7 @@ def test_version_decision_and_manifest(self): self.assertFalse(applies("v0.18.1")) self.assertTrue(applies("v0.19.0")) with self.assertRaises(RuntimeError): - applies("v0.20.0") + applies("v0.20.1") records = manifest("v0.19.0") self.assertEqual({r["source"] for r in records}, set(SOURCES)) self.assertEqual(manifest("v0.18.1"), []) @@ -56,15 +56,17 @@ def test_policy_and_identity_compile_against_crypto(self): "set exact upstream source root to audit patch application") def test_exact_source_patch_and_idempotence(self): source = Path(os.environ["LITERT_GPU_SAFETY_SOURCE"]) + tag = os.environ.get("LITERT_GPU_SAFETY_TAG", "v0.19.0") + sources = sources_for(tag) with tempfile.TemporaryDirectory() as temp: root = Path(temp) - for name in SOURCES: + for name in sources: target = root / name target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(source / name, target) - apply(root, "v0.19.0") - apply(root, "v0.19.0") - for name, (_, post) in SOURCES.items(): + apply(root, tag) + apply(root, tag) + for name, (_, post) in sources.items(): self.assertEqual(digest(root / name), post) text = (root / "c/engine.cc").read_text() start = text.index("LiteRtLmStatusCode litert_lm_engine_create(\n") @@ -76,9 +78,14 @@ def test_exact_source_patch_and_idempotence(self): unit = root / "engine_test.cc" selected = body if mutation: - selected = selected.replace( - "if (!safety.ok()) return litert::lm::c::ToCStatus(safety);", - "// Evidence control: ignore preflight refusal.") + refusal = ( + "LITERT_LM_C_RETURN_IF_ERROR(\n" + " litert_lm_native::PrepareAndroidGpuSafety(guarded_settings));" + if tag == "v0.20.0" + else "if (!safety.ok()) return litert::lm::c::ToCStatus(safety);" + ) + self.assertIn(refusal, selected) + selected = selected.replace(refusal, "// Ignore preflight refusal.") unit.write_text(harness.replace("// PRODUCTION_ENGINE_CREATE", selected)) binary = root / ("mutant" if mutation else "guard") subprocess.run([compiler, "-std=c++17", "-Wall", "-Wextra", diff --git a/tools/test_build_upstream_runtime.py b/tools/test_build_upstream_runtime.py index 5eb24f5..94168a7 100644 --- a/tools/test_build_upstream_runtime.py +++ b/tools/test_build_upstream_runtime.py @@ -677,7 +677,7 @@ def test_spatial_staging_postimages_fail_on_drift_or_missing_files(self) -> None (source_root / "bazel-out").symlink_to(exec_root / "bazel-out", target_is_directory=True) sources = {} files = [] - for name in build_upstream_runtime.STAGE_SPATIAL_TENSORS_SOURCES: + for name in build_upstream_runtime.stage_spatial_tensors_identity("v0.19.1")[3]: postimage = name.encode() + b"\n" sources[name] = ("", build_upstream_runtime.source_sha256(postimage)) file = output_base / "external" / "litert" / name @@ -685,7 +685,8 @@ def test_spatial_staging_postimages_fail_on_drift_or_missing_files(self) -> None file.write_bytes(postimage.replace(b"\n", b"\r\n")) files.append(file) - with patch.object(build_upstream_runtime, "STAGE_SPATIAL_TENSORS_SOURCES", sources): + with patch.object(build_upstream_runtime, "stage_spatial_tensors_identity", + return_value=("", "", "", sources)): build_upstream_runtime.verify_stage_spatial_tensors_postimages(source_root) for file in files: with self.subTest(file=file.name): diff --git a/tools/test_huggingface_token_bytes_patch.py b/tools/test_huggingface_token_bytes_patch.py index 4ed4f2c..c60c099 100644 --- a/tools/test_huggingface_token_bytes_patch.py +++ b/tools/test_huggingface_token_bytes_patch.py @@ -20,7 +20,7 @@ def test_unknown_releases_need_a_new_byte_contract_decision(self) -> None: self.assertFalse(carry.require_token_bytes_patch_decision(tag)) self.assertEqual(carry.token_bytes_patch_manifest(tag), []) self.assertTrue(carry.require_token_bytes_patch_decision("v0.19.0")) - for tag in ("v0.19.2", "v0.20.0", "main"): + for tag in ("v0.19.2", "v0.20.1", "main"): with self.subTest(tag=tag), self.assertRaisesRegex(RuntimeError, "no explicit decision"): carry.require_token_bytes_patch_decision(tag) diff --git a/tools/test_litert_lm_finish_reason_smoke.py b/tools/test_litert_lm_finish_reason_smoke.py index fb04cfa..49b8201 100644 --- a/tools/test_litert_lm_finish_reason_smoke.py +++ b/tools/test_litert_lm_finish_reason_smoke.py @@ -98,6 +98,19 @@ def test_abi_only_main_fails_when_the_in_process_marker_mismatches(self) -> None redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): self.assertEqual(smoke.main(), expected_status) + def test_v020_abi_only_requires_c_api_1_1_0(self) -> None: + argv = ["smoke", "--library", "runtime.so", "--abi-only", + "--upstream-tag", "v0.20.0"] + library = SimpleNamespace( + stream_proxy_finish_reason_abi_version=Mock(return_value=1), + litert_lm_native_in_process_litert_abi_version=Mock(return_value=1), + ) + for version, expected in (((1, 0, 0), 1), ((1, 1, 0), 0), ((1, 2, 0), 1)): + api = SimpleNamespace(library=library, api_version=lambda: version) + with self.subTest(version=version), patch.object(sys, "argv", argv), \ + patch.object(smoke, "bind", return_value=api), redirect_stdout(io.StringIO()): + self.assertEqual(smoke.main(), expected) + if __name__ == "__main__": unittest.main() diff --git a/tools/test_qualification_scheduling.py b/tools/test_qualification_scheduling.py index 2f4af49..73595af 100644 --- a/tools/test_qualification_scheduling.py +++ b/tools/test_qualification_scheduling.py @@ -53,7 +53,8 @@ def test_asr_job_executes_real_source_and_negative_mutations(self) -> None: self.assertIn('python3 -m unittest discover -s tools -p test_android_gpu_safety.py', asr) self.assertIn('pkg-config --exists openssl', asr) self.assertIn('tools/qualify_asr_untimed_overlap.py', asr) - self.assertIn('--source-root asr-upstream --work-dir asr-qualification --mutations', asr) + self.assertIn('--source-root asr-upstream --work-dir asr-qualification', asr) + self.assertIn('--upstream-tag "$QUALIFICATION_UPSTREAM_TAG" --mutations', asr) self.assertNotIn('continue-on-error:', asr) def test_candidate_check_reports_every_unsuccessful_prerequisite(self) -> None: diff --git a/tools/test_runtime_dependency_utils.py b/tools/test_runtime_dependency_utils.py index 09ee6d9..23b9a29 100644 --- a/tools/test_runtime_dependency_utils.py +++ b/tools/test_runtime_dependency_utils.py @@ -53,10 +53,12 @@ def write_elf_with_flags(path: Path, flags: int | None) -> None: path.write_bytes(data) -def write_elf_with_exports(path: Path, symbols: list[str]) -> None: +def write_elf_with_exports( + path: Path, symbols: list[str], *, imports: tuple[str, ...] = () +) -> None: string_table = bytearray(b"\0") name_offsets: list[int] = [] - for symbol in symbols: + for symbol in [*symbols, *imports]: name_offsets.append(len(string_table)) string_table.extend(symbol.encode("utf-8") + b"\0") @@ -66,7 +68,7 @@ def write_elf_with_exports(path: Path, symbols: list[str]) -> None: string_offset = section_header_offset + section_header_size * section_header_count symbol_offset = (string_offset + len(string_table) + 7) & ~7 symbol_entry_size = 24 - symbol_table_size = symbol_entry_size * (len(symbols) + 1) + symbol_table_size = symbol_entry_size * (len(name_offsets) + 1) data = bytearray(symbol_offset + symbol_table_size) data[:16] = b"\x7fELF\x02\x01\x01" + bytes(9) struct.pack_into( @@ -127,7 +129,7 @@ def write_elf_with_exports(path: Path, symbols: list[str]) -> None: name_offset, (1 << 4) | 2, 0, - 1, + 1 if index <= len(symbols) else 0, 0, 0, ) @@ -135,6 +137,23 @@ def write_elf_with_exports(path: Path, symbols: list[str]) -> None: class RuntimeDependencyUtilsTest(unittest.TestCase): + def test_android_dawn_override_must_cover_the_host_imports(self) -> None: + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + host = root / "bin/android/arm64/libLiteRtLm.so" + dawn = host.with_name("libwebgpu_dawn.so") + host.parent.mkdir(parents=True) + samplers = ANDROID_OPENCL_SAMPLER_SYMBOLS + ANDROID_WEBGPU_SAMPLER_SYMBOLS + write_elf_with_exports(host, samplers, imports=("wgpuQueueSubmit", "malloc")) + self.assertEqual(runtime_dependency_utils.elf_exported_symbols(host), set(samplers)) + write_elf_with_exports(dawn, []) + with patch("validate_runtime_dependencies.elf_has_global_flag", return_value=True), \ + patch("validate_runtime_dependencies.validate_android_protobuf_isolation"): + with self.assertRaisesRegex(SystemExit, "absent from .*: wgpuQueueSubmit"): + validate_elf_dependencies(root, "v0.20.0") + write_elf_with_exports(dawn, ["wgpuQueueSubmit"]) + self.assertEqual(validate_elf_dependencies(root, "v0.20.0"), 2) + def test_newest_glibc_requirement_compares_numerically(self) -> None: with tempfile.TemporaryDirectory() as temp: library = Path(temp) / "lib.so" diff --git a/tools/test_step_zero_state_patch.py b/tools/test_step_zero_state_patch.py index 8bfe2e6..4d2661b 100644 --- a/tools/test_step_zero_state_patch.py +++ b/tools/test_step_zero_state_patch.py @@ -18,13 +18,14 @@ def test_manifest_attributes_only_the_v0191_executor(self) -> None: self.assertEqual(records, [{ "id": "step-zero-state", "path": carry.PATCH_PATH, - "sha256": hashlib.sha256(carry.PATCH.read_bytes()).hexdigest(), + "sha256": hashlib.sha256((Path(__file__).resolve().parents[1] / carry.PATCH_PATH).read_bytes()).hexdigest(), "source": carry.SOURCE, "preimageSha256Lf": carry.PREIMAGE, "postimageSha256Lf": "b2c73fbcb400654072bf926dbaa3b81e252acf750f8fc1a60dd0b51df84d890d", "scope": "source-built runtimes only; excludes official upstream prebuilts", }]) - headers = [line for line in carry.PATCH.read_text().splitlines() + patch_path = Path(__file__).resolve().parents[1] / carry.PATCH_PATH + headers = [line for line in patch_path.read_text().splitlines() if line.startswith(("--- ", "+++ "))] self.assertEqual(headers, [f"--- a/{carry.SOURCE}", f"+++ b/{carry.SOURCE}"]) @@ -38,7 +39,7 @@ def test_version_bound_application_is_idempotent_and_rejects_wrong_source(self) patch_path = root / "fixture.patch" patch_path.write_text(f"--- a/{carry.SOURCE}\n+++ b/{carry.SOURCE}\n" "@@ -1 +1 @@\n-old executor\n+new executor\n") - with (patch.object(carry, "PATCH", patch_path), + with (patch.object(carry, "PATCH_PATH", str(patch_path)), patch.object(carry, "PREIMAGE", hashlib.sha256(before).hexdigest()), patch.object(carry, "POSTIMAGE", hashlib.sha256(after).hexdigest())): source.write_bytes(before) diff --git a/tools/test_v0181_qualification.py b/tools/test_v0181_qualification.py index 7161891..66fd8bc 100644 --- a/tools/test_v0181_qualification.py +++ b/tools/test_v0181_qualification.py @@ -103,8 +103,8 @@ def test_gpu_teardown_selection_follows_last_starlark_assignment(self): def test_qualification_workflow_uses_exact_stable_candidate(self): workflow = (REPO / ".github/workflows/pr_release_qualification.yml").read_text() - self.assertIn("QUALIFICATION_UPSTREAM_TAG: v0.19.1", workflow) - self.assertIn("QUALIFICATION_UPSTREAM_COMMIT: 7a03724cece417f1724c923b3d527b4319730841", workflow) + self.assertIn("QUALIFICATION_UPSTREAM_TAG: v0.20.0", workflow) + self.assertIn("QUALIFICATION_UPSTREAM_COMMIT: 95df4c2a932b4917ace66fcfef6c154e8d2a6699", workflow) if __name__ == "__main__": diff --git a/tools/test_v020_decisions.py b/tools/test_v020_decisions.py new file mode 100644 index 0000000..87f592a --- /dev/null +++ b/tools/test_v020_decisions.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +import unittest + +from asr_overlap_patch import source_patch_manifest +from prebuilt_overrides import prebuilt_overrides +from xnnpack_pf32_sme2_patch import commit_for + + +class V020DecisionsTest(unittest.TestCase): + def test_manifest_keeps_audited_carries_with_new_source_identities(self) -> None: + previous = source_patch_manifest("v0.19.1") + records = source_patch_manifest("v0.20.0") + self.assertEqual({r["id"] for r in records}, {r["id"] for r in previous}) + self.assertEqual(len(records), len(previous) + 1) + self.assertEqual(len({(r["id"], r["source"]) for r in records}), len(records)) + by_id = {r["id"]: r for r in records} + for patch_id in ( + "android-qwen3-gpu-safety", "huggingface-token-bytes", + "stream-finish-reason", "step-zero-state", "litert-stage-spatial-tensors", + ): + self.assertTrue(by_id[patch_id]["path"].endswith("_v020.patch")) + self.assertEqual( + by_id["asr-untimed-overlap"]["path"], "native/bridge/asr_untimed_overlap_v019.patch", + ) + self.assertEqual(commit_for("v0.20.0"), "08cc38b61f7589f84e91c6e343e0f130ae3279ca") + self.assertEqual(prebuilt_overrides("v0.20.0"), prebuilt_overrides("v0.19.1")) + with self.assertRaisesRegex(RuntimeError, "no explicit decision"): + source_patch_manifest("v0.20.1") diff --git a/tools/validate_runtime_dependencies.py b/tools/validate_runtime_dependencies.py index e2c68da..9724bad 100644 --- a/tools/validate_runtime_dependencies.py +++ b/tools/validate_runtime_dependencies.py @@ -13,6 +13,7 @@ from runtime_dependency_utils import ( elf_exported_symbols, elf_has_global_flag, + elf_imported_symbols, elf_load_alignments, elf_needed_libraries, is_elf, @@ -21,6 +22,7 @@ from litert_lm_symbols import ( ANDROID_OPENCL_SAMPLER_SYMBOLS, android_static_gpu_sampler_symbols, + is_at_least, APPLE_METAL_ACCELERATOR_SYMBOLS, APPLE_METAL_SAMPLER_SYMBOLS, ) @@ -115,6 +117,18 @@ def validate_elf_dependencies(root: Path, upstream_tag: str) -> int: "sampler plugins." ) if library.name == "libLiteRtLm.so": + if is_at_least(upstream_tag, (0, 20, 0)): + dawn = library.with_name("libwebgpu_dawn.so") + if dawn.is_file(): + missing_dawn = sorted( + {name for name in elf_imported_symbols(library) + if name.startswith("wgpu")} - elf_exported_symbols(dawn) + ) + if missing_dawn: + errors.append( + f"{library.relative_to(root).as_posix()} imports Dawn symbols " + f"absent from {dawn.name}: {', '.join(missing_dawn)}" + ) try: validate_android_protobuf_isolation(library, platform, upstream_tag) except RuntimeError as error: diff --git a/tools/workspace_build_patch.py b/tools/workspace_build_patch.py index 8c214b6..562459c 100644 --- a/tools/workspace_build_patch.py +++ b/tools/workspace_build_patch.py @@ -12,7 +12,7 @@ AUDITED_TAGS = frozenset({"v0.18.1"}) # v0.19.0 and v0.19.1 descend from UPSTREAM_EQUIVALENT and declare the same # plumbing. -UPSTREAM_FIX_TAGS = frozenset({"v0.19.0", "v0.19.1"}) +UPSTREAM_FIX_TAGS = frozenset({"v0.19.0", "v0.19.1", "v0.20.0"}) # LF-normalized (preimage, postimage) SHA-256 per patched v0.18.1 file. SOURCES = { ".bazelrc": ( diff --git a/tools/xnnpack_pf32_sme2_patch.py b/tools/xnnpack_pf32_sme2_patch.py index 3f68e74..21c8111 100644 --- a/tools/xnnpack_pf32_sme2_patch.py +++ b/tools/xnnpack_pf32_sme2_patch.py @@ -4,7 +4,7 @@ from pathlib import Path PATCH_PATH = "native/bridge/xnnpack_pf32_sme2.patch" -AUDITED_TAGS = frozenset({"v0.18.1", "v0.19.0", "v0.19.1"}) +AUDITED_TAGS = frozenset({"v0.18.1", "v0.19.0", "v0.19.1", "v0.20.0"}) # v0.18.1 pins TensorFlow a1179d3c, whose XLA pins this XNNPACK. It contains # 70a9c5e8ac, which moved the PF32 SME2 GEMM/GEMV to KleidiAI kernels that are # nondeterministic with more than one thread (google/XNNPACK#11789). The patch @@ -49,6 +49,28 @@ ), } +V020_TENSORFLOW_REF = "faa06da43657488c1f7479289d11d15e03a15ba1" +V020_XNNPACK_COMMIT = "08cc38b61f7589f84e91c6e343e0f130ae3279ca" +V020_XNNPACK_SHA256 = "1c94d80ff3069b3510e54b41a2c82729a4053724a682fcb09840af296dcaa07c" +V020_SOURCES = { + "src/configs/gemm-config.c": ( + "77f6499beb82d69ca19dd9ca31a7c591b07c78863c158701b1125dcee0bb843d", + "0eff752814ec351176c48461832907ab8841c81d06c330483dae1cf45d233a9c", + ), + "src/pf32-gemm/pf32-gemm-1x32-minmax-neonsme2.c": ( + "777115eb004977880b26ec4313d94a09f73157cbc44f3196585a1497411cbcc7", + "5d9972ed94ad8382fa184ffd66709cccaf932aa2a20b91b419834ca45c04f7b8", + ), + "src/pf32-gemm/pf32-gemm-32x32-minmax-neonsme2.c": ( + "f101b386705e62f257c8c7e613474dd811d968316e968e2ff415fefe064f3abe", + "aa692a7cfbfa6c88df6185caba1938502842d92219c9fe3e728cf1a08aa95301", + ), + "src/x32-pack-lh/x32-packlh-neonsme2.c": ( + "820b6c397d740e63efb03ab23be9a0c337b147a302dbce139ddcf55b7b8216f8", + "5aa0176053653592a86ebc848261029f2494e23f9c9be25cc9923afc901345c0", + ), +} + def archive(tensorflow_ref: str, commit: str, sha256: str) -> str: # Declared ahead of tf_workspace2(): XLA's tf_http_archive skips a repository @@ -80,6 +102,9 @@ def archive(tensorflow_ref: str, commit: str, sha256: str) -> str: ARCHIVE = archive(TENSORFLOW_REF, XNNPACK_COMMIT, XNNPACK_SHA256) ARCHIVES = { TENSORFLOW_REF: ARCHIVE, + V020_TENSORFLOW_REF: archive( + V020_TENSORFLOW_REF, V020_XNNPACK_COMMIT, V020_XNNPACK_SHA256 + ), V019_TENSORFLOW_REF: archive( V019_TENSORFLOW_REF, V019_XNNPACK_COMMIT, V019_XNNPACK_SHA256 ), @@ -87,14 +112,20 @@ def archive(tensorflow_ref: str, commit: str, sha256: str) -> str: def sources_for(compatibility_tag: str) -> dict[str, tuple[str, str]]: + if compatibility_tag == "v0.20.0": + return V020_SOURCES return V019_SOURCES if compatibility_tag in V019_TAGS else SOURCES def commit_for(compatibility_tag: str) -> str: + if compatibility_tag == "v0.20.0": + return V020_XNNPACK_COMMIT return V019_XNNPACK_COMMIT if compatibility_tag in V019_TAGS else XNNPACK_COMMIT def archive_sha256_for(compatibility_tag: str) -> str: + if compatibility_tag == "v0.20.0": + return V020_XNNPACK_SHA256 return V019_XNNPACK_SHA256 if compatibility_tag in V019_TAGS else XNNPACK_SHA256 @@ -117,6 +148,8 @@ def require_xnnpack_pf32_patch_decision(compatibility_tag: str) -> bool: def verify_patched_xnnpack_archive(workspace: str, compatibility_tag: str) -> None: tensorflow_ref = V019_TENSORFLOW_REF if compatibility_tag in V019_TAGS else TENSORFLOW_REF + if compatibility_tag == "v0.20.0": + tensorflow_ref = V020_TENSORFLOW_REF if (workspace.count(ARCHIVES[tensorflow_ref] + TENSORFLOW_ARCHIVE) != 1 or len(re.findall(r'^\s*name = "XNNPACK",$', workspace, re.MULTILINE)) != 1): raise RuntimeError("Unexpected XNNPACK archive in WORKSPACE; requalify the XNNPACK patches") diff --git a/tools/xnnpack_pqs8_qc4w_sme2_patch.py b/tools/xnnpack_pqs8_qc4w_sme2_patch.py index dc79e03..6d64131 100644 --- a/tools/xnnpack_pqs8_qc4w_sme2_patch.py +++ b/tools/xnnpack_pqs8_qc4w_sme2_patch.py @@ -33,8 +33,17 @@ ), } +V020_SOURCES = { + "src/configs/gemm-config.c": ( + "0eff752814ec351176c48461832907ab8841c81d06c330483dae1cf45d233a9c", + "3bad8691babc6044975b8720fd88be0e7e420322533330f108df2901ca15110d", + ), +} + def sources_for(compatibility_tag: str) -> dict[str, tuple[str, str]]: + if compatibility_tag == "v0.20.0": + return V020_SOURCES return V019_SOURCES if compatibility_tag in V019_TAGS else SOURCES From 3b3ffeb8e8235c219296d8a5b86076a007326331 Mon Sep 17 00:00:00 2001 From: leehack Date: Mon, 23 Nov 2026 23:32:19 -0500 Subject: [PATCH 2/9] Check the renamed LiteRT OpenCL initializer --- tools/gpu_environment_teardown.py | 5 +++-- tools/test_gpu_environment_teardown.py | 15 ++++++++++----- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/tools/gpu_environment_teardown.py b/tools/gpu_environment_teardown.py index fc4bef5..6d1a4f0 100644 --- a/tools/gpu_environment_teardown.py +++ b/tools/gpu_environment_teardown.py @@ -26,12 +26,13 @@ "_ZN6litert8internal27CreateGpuEnvironmentOptions" "ERK25LiteRtEnvironmentOptionsT" ) -# LiteRT 9c8ae4e0fc moved the OpenCL setup, and with it the LoadOpenCL call, -# into GpuEnvironment::InitializeOpenCl. +# LiteRT first moved LoadOpenCL into InitializeOpenCl and then renamed that +# entry point to InitializeOpenClLocked when setup became lazy. OPENCL_SETUP_SYMBOLS = frozenset( { "_ZN6tflite3gpu2cl10LoadOpenCLEv", "_ZN6litert8internal14GpuEnvironment16InitializeOpenClEv", + "_ZN6litert8internal14GpuEnvironment22InitializeOpenClLockedEv", } ) diff --git a/tools/test_gpu_environment_teardown.py b/tools/test_gpu_environment_teardown.py index f6c7243..f0e59d1 100644 --- a/tools/test_gpu_environment_teardown.py +++ b/tools/test_gpu_environment_teardown.py @@ -51,11 +51,16 @@ def test_patched_libraries_record_the_options_first(self) -> None: teardown.check_initialize_disassembly(fixture(f"android_{arch}_patched")) def test_reordered_upstream_shape_passes_and_its_reverse_fails(self) -> None: - teardown.check_initialize_disassembly(REORDERED_UPSTREAM) - lines = REORDERED_UPSTREAM.splitlines() - lines[7], lines[8] = lines[8], lines[7] - with self.assertRaisesRegex(RuntimeError, "sets up OpenCL before"): - teardown.check_initialize_disassembly("\n".join(lines)) + for disassembly in ( + REORDERED_UPSTREAM, + REORDERED_UPSTREAM.replace("16InitializeOpenClEv", "22InitializeOpenClLockedEv"), + ): + with self.subTest(disassembly=disassembly): + teardown.check_initialize_disassembly(disassembly) + lines = disassembly.splitlines() + lines[7], lines[8] = lines[8], lines[7] + with self.assertRaisesRegex(RuntimeError, "sets up OpenCL before"): + teardown.check_initialize_disassembly("\n".join(lines)) def test_missing_function_or_call_is_an_error(self) -> None: with self.assertRaisesRegex(RuntimeError, "was not found"): From 4c7fc3b942a6cb9d0624345b149852124feaecfa Mon Sep 17 00:00:00 2001 From: leehack Date: Mon, 23 Nov 2026 23:48:14 -0500 Subject: [PATCH 3/9] Apply HF grammar patch inside nested source trees --- docs/upstream_patch_audit.md | 15 +++++++++ tools/huggingface_token_bytes_patch.py | 22 ++++++++----- tools/test_huggingface_token_bytes_patch.py | 34 +++++++++++++++++++++ 3 files changed, 64 insertions(+), 7 deletions(-) diff --git a/docs/upstream_patch_audit.md b/docs/upstream_patch_audit.md index 5badd77..dedc3ad 100644 --- a/docs/upstream_patch_audit.md +++ b/docs/upstream_patch_audit.md @@ -283,6 +283,21 @@ the UTF-8 callback contract and bounded-default formatting policy pass these controls, and the unchanged supported-model schema qualifier, including literal Unicode keys/values, succeeds against the packaged runtime. +### v0.20.0 requalification + +Upstream added SentencePiece byte fallback and LLGuidance multiple-EOS support. +It still reads raw HF vocabulary spellings without ByteLevel inversion. Its +text callback uses the UTF-8 contract by default. When the verbatim probe +fails, upstream removes the callback and enables approximate trie tokenization. +The v0.20.0 carry derives ByteLevel bytes before this probe and preserves the +SentencePiece and multiple-EOS paths. + +The six pinned preimage and postimage hashes were re-derived from +`95df4c2a932b4917ace66fcfef6c154e8d2a6699`. Run the qualifier with +`--upstream-tag v0.20.0` against that checkout. The apply step bounds Git +repository discovery to the copied source tree so it can patch the default +qualification directory inside the owner checkout. + ### Default JSON formatting progress The PR103 Mac diagnostic primary (`1a29401a…`) fixed the native abort but the diff --git a/tools/huggingface_token_bytes_patch.py b/tools/huggingface_token_bytes_patch.py index f732e95..6cce1e5 100644 --- a/tools/huggingface_token_bytes_patch.py +++ b/tools/huggingface_token_bytes_patch.py @@ -1,5 +1,6 @@ """Identity and fail-closed application of the HF ByteLevel grammar fix (#100).""" import hashlib +import os import re import subprocess from pathlib import Path @@ -90,17 +91,24 @@ def _digest(path: Path) -> str: def apply(source_root: Path, tag: str) -> None: if not require_token_bytes_patch_decision(tag): return - digests = {name: _digest(source_root / name) for name in sources_for(tag)} - if all(digests[name] == post for name, (_, post) in sources_for(tag).items()): + sources = sources_for(tag) + digests = {name: _digest(source_root / name) for name in sources} + if all(digests[name] == post for name, (_, post) in sources.items()): return - if any(digests[name] != pre for name, (pre, _) in sources_for(tag).items()): + if any(digests[name] != pre for name, (pre, _) in sources.items()): raise RuntimeError("Tokenizer or grammar source changed; requalify #100 token bytes patch") patch = Path(__file__).resolve().parents[1] / patch_path_for(tag) command = ["git", "apply", "--ignore-space-change", str(patch)] - subprocess.run([*command[:2], "--check", *command[2:]], check=True, cwd=source_root) - subprocess.run(command, check=True, cwd=source_root) - if any(_digest(source_root / name) != post for name, (_, post) in sources_for(tag).items()): - raise RuntimeError("HuggingFace token bytes postimage mismatch; requalify #100") + # In a nested source copy, the owner's Git root can silently filter out hunks. + env = {**os.environ, "GIT_CEILING_DIRECTORIES": str(source_root.resolve().parent)} + subprocess.run([*command[:2], "--check", *command[2:]], check=True, cwd=source_root, env=env) + subprocess.run(command, check=True, cwd=source_root, env=env) + mismatches = [name for name, (_, post) in sources.items() + if _digest(source_root / name) != post] + if mismatches: + raise RuntimeError( + f"HuggingFace token bytes postimage mismatch for {', '.join(mismatches)}; " + "requalify #100") def token_bytes_patch_manifest(tag: str) -> list[dict]: diff --git a/tools/test_huggingface_token_bytes_patch.py b/tools/test_huggingface_token_bytes_patch.py index c60c099..7314d23 100644 --- a/tools/test_huggingface_token_bytes_patch.py +++ b/tools/test_huggingface_token_bytes_patch.py @@ -2,6 +2,7 @@ import hashlib import re +import subprocess import tempfile import unittest from pathlib import Path @@ -65,6 +66,39 @@ def test_successful_git_apply_must_match_every_postimage(self) -> None: with self.assertRaisesRegex(RuntimeError, "postimage mismatch"): carry.apply(root, "v0.19.0") + def test_nested_v020_source_applies_and_rejects_a_drifted_postimage(self) -> None: + with tempfile.TemporaryDirectory() as temp: + repo = Path(temp) + subprocess.run(["git", "init", "--quiet", str(repo)], check=True) + root = repo / "token-byte-qualification" / "patched" + root.mkdir(parents=True) + (repo / "tokenizer.h").write_bytes(b"owner header\n") + source = root / "tokenizer.h" + preimage = b"context\nraw spelling\n" + postimage = b"context\nexact bytes\n" + sources = {"tokenizer.h": (hashlib.sha256(preimage).hexdigest(), + hashlib.sha256(postimage).hexdigest())} + patch_file = repo / "fixture.patch" + patch_file.write_bytes( + b"diff --git a/tokenizer.h b/tokenizer.h\n" + b"--- a/tokenizer.h\n+++ b/tokenizer.h\n" + b"@@ -1,2 +1,2 @@\n context\n-raw spelling\n+exact bytes\n" + ) + with (patch.object(carry, "V020_SOURCES", sources), + patch.object(carry, "V020_PATCH_PATH", str(patch_file))): + source.write_bytes(preimage) + carry.apply(root, "v0.20.0") + self.assertEqual(source.read_bytes(), postimage) + self.assertEqual((repo / "tokenizer.h").read_bytes(), b"owner header\n") + carry.apply(root, "v0.20.0") + + source.write_bytes(preimage) + patch_file.write_bytes(patch_file.read_bytes().replace( + b"+exact bytes", b"+unqualified bytes")) + with self.assertRaisesRegex(RuntimeError, "postimage mismatch"): + carry.apply(root, "v0.20.0") + self.assertEqual(source.read_bytes(), b"context\nunqualified bytes\n") + def test_reference_uses_special_ids_and_keeps_partial_utf8_and_all_slots(self) -> None: fixture = vocabulary_fixture({"model": {"vocab": {"Ã": 0, "©": 1, "Ā": 2}}, "decoder": {"type": "ByteLevel"}, From e512a2f57a004a20f704bec51cd3af5cbb20f4fe Mon Sep 17 00:00:00 2001 From: leehack Date: Tue, 24 Nov 2026 00:52:38 -0500 Subject: [PATCH 4/9] Apply Git-format patches from the upstream source root --- tools/android_gpu_safety_patch.py | 8 ++-- tools/build_upstream_runtime.py | 6 +-- tools/huggingface_token_bytes_patch.py | 10 ++--- tools/source_patch_utils.py | 16 ++++++++ tools/step_zero_state_patch.py | 8 ++-- tools/test_huggingface_token_bytes_patch.py | 8 ++-- tools/test_step_zero_state_patch.py | 6 +-- tools/test_v020_decisions.py | 42 ++++++++++++++++++++- 8 files changed, 77 insertions(+), 27 deletions(-) create mode 100644 tools/source_patch_utils.py diff --git a/tools/android_gpu_safety_patch.py b/tools/android_gpu_safety_patch.py index a35deb5..bbe67db 100644 --- a/tools/android_gpu_safety_patch.py +++ b/tools/android_gpu_safety_patch.py @@ -1,8 +1,9 @@ """Audited C API preflight patch for the exact Android Qwen3 safety policy.""" import hashlib -from pathlib import Path import re -import subprocess +from pathlib import Path + +from source_patch_utils import apply_source_patch PATCH_PATH = "native/bridge/android_gpu_safety_v019.patch" # v0.19.1 leaves c/engine.cc and c/BUILD byte-identical to v0.19.0. @@ -56,8 +57,7 @@ def apply(source_root: Path, tag: str) -> None: if any(observed[name] != pre for name, (pre, _) in sources_for(tag).items()): raise RuntimeError("C API safety source changed; requalify Android GPU preflight") patch = Path(__file__).resolve().parents[1] / patch_path_for(tag) - subprocess.run(["git", "apply", "--check", str(patch)], cwd=source_root, check=True) - subprocess.run(["git", "apply", str(patch)], cwd=source_root, check=True) + apply_source_patch(source_root, patch) if any(digest(source_root / name) != post for name, (_, post) in sources_for(tag).items()): raise RuntimeError("Android GPU preflight postimage mismatch") diff --git a/tools/build_upstream_runtime.py b/tools/build_upstream_runtime.py index d9a08eb..46d1a30 100644 --- a/tools/build_upstream_runtime.py +++ b/tools/build_upstream_runtime.py @@ -54,6 +54,7 @@ is_elf, is_system_needed, ) +from source_patch_utils import apply_source_patch from step_zero_state_patch import apply as patch_step_zero_state from stream_finish_reason_patch import ( BAZEL_DEFINE as FINISH_REASON_DEFINE, @@ -256,10 +257,7 @@ def patch_stream_finish_reason(source_root: Path, upstream_tag: str) -> None: "Decode or conversation source changed; requalify the stream " "finish-reason patch") patch_file = REPO_ROOT / finish_reason_patch_path(upstream_tag) - command = ["git", "apply", "--ignore-space-change", str(patch_file)] - subprocess.run([*command[:2], "--check", *command[2:]], check=True, - cwd=source_root) - subprocess.run(command, check=True, cwd=source_root) + apply_source_patch(source_root, patch_file, ignore_space_change=True) for name, (_, post) in sources.items(): if source_sha256((source_root / name).read_bytes()) != post: raise RuntimeError( diff --git a/tools/huggingface_token_bytes_patch.py b/tools/huggingface_token_bytes_patch.py index 6cce1e5..cbbd0d8 100644 --- a/tools/huggingface_token_bytes_patch.py +++ b/tools/huggingface_token_bytes_patch.py @@ -1,10 +1,10 @@ """Identity and fail-closed application of the HF ByteLevel grammar fix (#100).""" import hashlib -import os import re -import subprocess from pathlib import Path +from source_patch_utils import apply_source_patch + PATCH_PATH = "native/bridge/huggingface_token_bytes_v019.patch" AUDITED_TAGS = frozenset({"v0.19.0", "v0.19.1", "v0.20.0"}) # LF-normalized upstream v0.19.0 / 83ce6067 preimages and patched postimages; @@ -98,11 +98,7 @@ def apply(source_root: Path, tag: str) -> None: if any(digests[name] != pre for name, (pre, _) in sources.items()): raise RuntimeError("Tokenizer or grammar source changed; requalify #100 token bytes patch") patch = Path(__file__).resolve().parents[1] / patch_path_for(tag) - command = ["git", "apply", "--ignore-space-change", str(patch)] - # In a nested source copy, the owner's Git root can silently filter out hunks. - env = {**os.environ, "GIT_CEILING_DIRECTORIES": str(source_root.resolve().parent)} - subprocess.run([*command[:2], "--check", *command[2:]], check=True, cwd=source_root, env=env) - subprocess.run(command, check=True, cwd=source_root, env=env) + apply_source_patch(source_root, patch, ignore_space_change=True) mismatches = [name for name, (_, post) in sources.items() if _digest(source_root / name) != post] if mismatches: diff --git a/tools/source_patch_utils.py b/tools/source_patch_utils.py new file mode 100644 index 0000000..e1f25a0 --- /dev/null +++ b/tools/source_patch_utils.py @@ -0,0 +1,16 @@ +"""Apply audited patches relative to the upstream source root.""" + +import os +import subprocess +from pathlib import Path + + +def apply_source_patch( + source_root: Path, patch_file: Path, *, ignore_space_change: bool = False, +) -> None: + # An enclosing owner repository can silently filter out Git-format hunks. + env = {**os.environ, "GIT_CEILING_DIRECTORIES": source_root.resolve().parent.as_posix()} + args = ["--ignore-space-change"] if ignore_space_change else [] + args.append(str(patch_file)) + subprocess.run(["git", "apply", "--check", *args], check=True, cwd=source_root, env=env) + subprocess.run(["git", "apply", *args], check=True, cwd=source_root, env=env) diff --git a/tools/step_zero_state_patch.py b/tools/step_zero_state_patch.py index 69f52e4..de24015 100644 --- a/tools/step_zero_state_patch.py +++ b/tools/step_zero_state_patch.py @@ -1,9 +1,10 @@ """Version-bound step-zero reset and macOS linear-attention sampler policy.""" import hashlib import re -import subprocess from pathlib import Path +from source_patch_utils import apply_source_patch + PATCH_PATH = "native/bridge/step_zero_state_v0191.patch" SOURCE = "runtime/executor/llm_litert_compiled_model_executor.cc" PREIMAGE = "5e6898eb07178719c554ed49e4bc79d891badea4ad0576d00af54ef1bd8dbb4c" @@ -44,9 +45,8 @@ def apply(source_root: Path, tag: str) -> None: return if digest != preimage: raise RuntimeError("Executor source changed; requalify the step-zero state patch") - args = ["--ignore-space-change", str(Path(__file__).resolve().parents[1] / patch_path)] - subprocess.run(["git", "apply", "--check", *args], check=True, cwd=source_root) - subprocess.run(["git", "apply", *args], check=True, cwd=source_root) + patch = Path(__file__).resolve().parents[1] / patch_path + apply_source_patch(source_root, patch, ignore_space_change=True) if _digest(path) != postimage: raise RuntimeError("Executor step-zero state postimage mismatch") diff --git a/tools/test_huggingface_token_bytes_patch.py b/tools/test_huggingface_token_bytes_patch.py index 7314d23..f0c02dc 100644 --- a/tools/test_huggingface_token_bytes_patch.py +++ b/tools/test_huggingface_token_bytes_patch.py @@ -48,21 +48,21 @@ def test_mixed_or_unknown_source_is_refused_before_git_apply(self) -> None: "two": (hashlib.sha256(b"pre").hexdigest(), hashlib.sha256(b"post").hexdigest())} for name in sources: (root / name).write_bytes(b"post") - with patch.object(carry, "SOURCES", sources), patch.object(carry.subprocess, "run") as run: + with patch.object(carry, "SOURCES", sources), patch.object(carry, "apply_source_patch") as apply: carry.apply(root, "v0.19.0") - run.assert_not_called() + apply.assert_not_called() for contents in (b"pre", b"unrecognized"): (root / "one").write_bytes(contents) with self.assertRaisesRegex(RuntimeError, "source changed"): carry.apply(root, "v0.19.0") - run.assert_not_called() + apply.assert_not_called() def test_successful_git_apply_must_match_every_postimage(self) -> None: with tempfile.TemporaryDirectory() as temp: root = Path(temp) (root / "one").write_bytes(b"pre") sources = {"one": (hashlib.sha256(b"pre").hexdigest(), hashlib.sha256(b"post").hexdigest())} - with patch.object(carry, "SOURCES", sources), patch.object(carry.subprocess, "run"): + with patch.object(carry, "SOURCES", sources), patch.object(carry, "apply_source_patch"): with self.assertRaisesRegex(RuntimeError, "postimage mismatch"): carry.apply(root, "v0.19.0") diff --git a/tools/test_step_zero_state_patch.py b/tools/test_step_zero_state_patch.py index 4d2661b..1431b1b 100644 --- a/tools/test_step_zero_state_patch.py +++ b/tools/test_step_zero_state_patch.py @@ -45,15 +45,15 @@ def test_version_bound_application_is_idempotent_and_rejects_wrong_source(self) source.write_bytes(before) carry.apply(root, "v0.19.1") self.assertEqual(source.read_bytes(), after) - with patch.object(carry.subprocess, "run") as run: + with patch.object(carry, "apply_source_patch") as apply: carry.apply(root, "v0.19.1") source.write_bytes(b"unknown executor\n") with self.assertRaisesRegex(RuntimeError, "source changed"): carry.apply(root, "v0.19.1") - run.assert_not_called() + apply.assert_not_called() def test_application_requires_the_exact_postimage(self) -> None: with (patch.object(carry, "_digest", side_effect=[carry.PREIMAGE, "wrong"]), - patch.object(carry.subprocess, "run")): + patch.object(carry, "apply_source_patch")): with self.assertRaisesRegex(RuntimeError, "postimage mismatch"): carry.apply(Path("."), "v0.19.1") diff --git a/tools/test_v020_decisions.py b/tools/test_v020_decisions.py index 87f592a..73f2b31 100644 --- a/tools/test_v020_decisions.py +++ b/tools/test_v020_decisions.py @@ -1,13 +1,53 @@ from __future__ import annotations +import subprocess +import tempfile import unittest +from pathlib import Path +from unittest.mock import patch -from asr_overlap_patch import source_patch_manifest +import android_gpu_safety_patch +import step_zero_state_patch +import stream_finish_reason_patch +from asr_overlap_patch import source_patch_manifest, source_sha256 +from build_upstream_runtime import patch_stream_finish_reason from prebuilt_overrides import prebuilt_overrides from xnnpack_pf32_sme2_patch import commit_for class V020DecisionsTest(unittest.TestCase): + def test_git_format_carries_apply_inside_owner_checkout(self) -> None: + before = b"context\nupstream\n" + after = b"context\npatched\n" + hashes = source_sha256(before), source_sha256(after) + names_and_appliers = ( + (stream_finish_reason_patch, "c/c_api_internal.h", patch_stream_finish_reason, + {"V020_SOURCES": {"c/c_api_internal.h": hashes}}), + (step_zero_state_patch, step_zero_state_patch.SOURCE, step_zero_state_patch.apply, + {"V020_PREIMAGE": hashes[0], "V020_POSTIMAGE": hashes[1]}), + (android_gpu_safety_patch, "c/engine.cc", android_gpu_safety_patch.apply, + {"V020_SOURCES": {"c/engine.cc": hashes}}), + ) + with tempfile.TemporaryDirectory() as temp: + owner = Path(temp) + subprocess.run(["git", "init", "--quiet", str(owner)], check=True) + source_root = owner / ".tmp" / "litert-build" / "LiteRT-LM-v0.20.0" + patch_file = owner / "carry.patch" + for module, name, apply, identities in names_and_appliers: + with self.subTest(source=name): + source = source_root / name + source.parent.mkdir(parents=True, exist_ok=True) + source.write_bytes(before) + patch_file.write_bytes(( + f"diff --git a/{name} b/{name}\n" + f"--- a/{name}\n+++ b/{name}\n" + "@@ -1,2 +1,2 @@\n context\n-upstream\n+patched\n" + ).encode()) + with patch.multiple(module, V020_PATCH_PATH=str(patch_file), **identities): + apply(source_root, "v0.20.0") + self.assertEqual(source.read_bytes(), after) + self.assertFalse((owner / name).exists()) + def test_manifest_keeps_audited_carries_with_new_source_identities(self) -> None: previous = source_patch_manifest("v0.19.1") records = source_patch_manifest("v0.20.0") From 69b9c38a639120d2d0074434b0069cf379c28400 Mon Sep 17 00:00:00 2001 From: leehack Date: Tue, 24 Nov 2026 01:59:17 -0500 Subject: [PATCH 5/9] Apply TensorFlow Android rules patches without Bash on Windows --- native/bridge/BUILD.bazel | 1 + .../rules_android_tensorflow_v020.patch | 131 ++++++++++++++++++ tools/build_upstream_runtime.py | 35 +++++ tools/test_build_upstream_runtime.py | 47 +++++++ 4 files changed, 214 insertions(+) create mode 100644 native/bridge/rules_android_tensorflow_v020.patch diff --git a/native/bridge/BUILD.bazel b/native/bridge/BUILD.bazel index 04acffc..f6c3ae9 100644 --- a/native/bridge/BUILD.bazel +++ b/native/bridge/BUILD.bazel @@ -40,6 +40,7 @@ exports_files([ "litert_ios_framework_paths_v020.patch", "litert_stage_spatial_tensors.patch", "litert_stage_spatial_tensors_v020.patch", + "rules_android_tensorflow_v020.patch", "sentencepiece_bpe_null.patch", "stream_finish_reason.patch", "stream_finish_reason_v019.patch", diff --git a/native/bridge/rules_android_tensorflow_v020.patch b/native/bridge/rules_android_tensorflow_v020.patch new file mode 100644 index 0000000..1b027fb --- /dev/null +++ b/native/bridge/rules_android_tensorflow_v020.patch @@ -0,0 +1,131 @@ +diff --git a/toolchains/android_sdk/BUILD b/toolchains/android_sdk/BUILD +--- a/toolchains/android_sdk/BUILD ++++ b/toolchains/android_sdk/BUILD +@@ -31,5 +31,5 @@ + # "@bazel_tools//platforms:android", + #], +- toolchain = "@androidsdk//:sdk", ++ toolchain = ":toolchain_type", + toolchain_type = ":toolchain_type", + ) +@@ -37,5 +37,5 @@ + dummy_toolchain_dep( + name = "dummy_sdk_tools", +- sdk_toolchain = "@androidsdk//:sdk", ++ sdk_toolchain = ":toolchain_type", + visibility = ["//visibility:public"], + ) +diff --git a/tools/jdk/BUILD b/tools/jdk/BUILD +--- a/tools/jdk/BUILD ++++ b/tools/jdk/BUILD +@@ -53,5 +53,5 @@ + name = "toolchain_android_only", + bootclasspath = [ +- ":bootclasspath_android_only", ++ "@rules_java//toolchains:platformclasspath", + ], + visibility = ["//visibility:public"], +diff --git a/BUILD b/BUILD +--- a/BUILD ++++ b/BUILD +@@ -1,3 +1,2 @@ +-load("@bazel_gazelle//:def.bzl", "gazelle") + load("@rules_license//rules:license.bzl", "license") + +@@ -18,5 +17,4 @@ + + # gazelle:prefix github.com/bazelbuild/rules_android +-gazelle(name = "gazelle") + + # Common default platform definitions for use by Android projects. +diff --git a/tools/android/BUILD b/tools/android/BUILD +--- a/tools/android/BUILD ++++ b/tools/android/BUILD +@@ -53,5 +53,5 @@ + main_class = "com.android.tools.build.bundletool.BundleToolMain", + visibility = ["//visibility:public"], +- runtime_deps = ["@rules_android_maven//:com_android_tools_build_bundletool"], ++ runtime_deps = [], + ) + +@@ -103,7 +103,5 @@ + name = "desugar_jdk_libs_json", + srcs = select({ +- "full_desugaring": [":full_desugar_jdk_libs_config_json"], + "minimal_desugaring": [":minimal_desugar_jdk_libs_config_json"], +- "//conditions:default": [":full_desugar_jdk_libs_config_json"], + }), + outs = ["desugar_jdk_libs.json"], +@@ -143,9 +141,7 @@ + srcs = [ + ":desugared_jdk_libs_from_maven.jar", +- ":full_desugar_jdk_libs_config_json", + ], + outs = ["desugared_jdk_libs.jar"], + cmd = "$(location :desugar_java8) " + +- "--desugared_lib_config $(location :full_desugar_jdk_libs_config_json) " + + "--input=$(location :desugared_jdk_libs_from_maven.jar) --output=$@", + tools = [":desugar_java8"], +@@ -187,7 +183,4 @@ + srcs = [":d8_desugar.sh"], + data = [ +- ":d8_desugar_params", +- ":full_desugar_jdk_libs_config_json", +- "//src/tools/java/com/google/devtools/build/android/r8:desugar", + "@bazel_tools//tools/bash/runfiles", + ], +@@ -204,5 +197,5 @@ + name = "desugared_java8_legacy_apis", + constraints = ["android"], +- jars = [":ijar_desugared_java8_legacy_libs"], ++ jars = [], + neverlink = 1, + visibility = ["//visibility:public"], +@@ -213,5 +206,5 @@ + main_class = "com.android.tools.r8.D8", + visibility = ["//visibility:public"], +- runtime_deps = ["@rules_android_maven//:com_android_tools_r8"], ++ runtime_deps = [], + ) + +@@ -220,5 +213,5 @@ + main_class = "com.android.tools.r8.R8", + visibility = ["//visibility:public"], +- runtime_deps = ["@rules_android_maven//:com_android_tools_r8"], ++ runtime_deps = [], + ) + +@@ -227,5 +220,5 @@ + main_class = "com.android.tools.r8.tracereferences.TraceReferences", + visibility = ["//visibility:public"], +- runtime_deps = ["@rules_android_maven//:com_android_tools_r8"], ++ runtime_deps = [], + ) + +@@ -234,5 +227,5 @@ + main_class = "com.android.build.shrinker.ResourceShrinkerCli", + visibility = ["//visibility:public"], +- runtime_deps = ["@rules_android_maven//:com_android_tools_build_gradle"], ++ runtime_deps = [], + ) + +@@ -270,5 +263,5 @@ + main_class = "com.google.devtools.build.android.r8.CompatDexBuilder", + visibility = ["//visibility:private"], +- runtime_deps = ["//src/tools/java/com/google/devtools/build/android/r8"], ++ runtime_deps = [], + ) + +@@ -295,5 +288,5 @@ + main_class = "com.google.devtools.build.android.r8.DexFileMerger", + visibility = ["//visibility:private"], +- runtime_deps = ["//src/tools/java/com/google/devtools/build/android/r8"], ++ runtime_deps = [], + ) + +@@ -308,4 +301,4 @@ + ], + main_class = "com.android.tools.r8.GlobalSyntheticsGenerator", +- runtime_deps = ["@rules_android_maven//:com_android_tools_r8"], ++ runtime_deps = [], + ) diff --git a/tools/build_upstream_runtime.py b/tools/build_upstream_runtime.py index 46d1a30..ad301df 100644 --- a/tools/build_upstream_runtime.py +++ b/tools/build_upstream_runtime.py @@ -70,6 +70,7 @@ require_workspace_build_patch_decision, ) from xnnpack_pf32_sme2_patch import ( + V020_TENSORFLOW_REF, archive_sha256_for as xnnpack_archive_sha256, commit_for as xnnpack_commit, declare_patched_xnnpack, @@ -528,6 +529,38 @@ def patch_upstream_workspace( ) +def patch_windows_rules_android(source_root: Path) -> None: + workspace = source_root / "WORKSPACE" + text = workspace.read_text(encoding="utf-8") + refs = re.findall(r'^TENSORFLOW_REF[ \t]*=[ \t]*"([0-9a-f]{40})"$', text, re.MULTILINE) + if refs != [V020_TENSORFLOW_REF]: + raise RuntimeError("TensorFlow pin changed; requalify the Windows rules_android patch") + + # TensorFlow skips repos declared before tf_workspace2(). Use its archive + # and all four source edits without its Bash/sed repository commands. + url = "https://github.com/bazelbuild/rules_android/releases/download/v0.6.0/rules_android-v0.6.0.tar.gz" + archive = f'''http_archive( + name = "build_bazel_rules_android", + patch_args = ["-p1"], + patches = ["@//bridge:rules_android_tensorflow_v020.patch"], + sha256 = "af84b69ab3d16dd1a41056286e6511f147a94ccea995603e13e934c915c1631c", + strip_prefix = "rules_android-0.6.0", + urls = [ + "https://storage.googleapis.com/mirror.tensorflow.org/{url[8:]}", + "{url}", + ], +) + +''' + hook = '\nload("@org_tensorflow//tensorflow:workspace2.bzl", "tf_workspace2")\n' + declarations = re.findall(r'^\s*name\s*=\s*"build_bazel_rules_android"\s*,', text, re.MULTILINE) + if text.count("\n" + archive + hook) == 1 and len(declarations) == 1: + return + if declarations or text.count(hook) != 1: + raise RuntimeError("Unexpected Windows rules_android declaration point in WORKSPACE; requalify") + workspace.write_text(text.replace(hook, "\n" + archive + hook, 1), encoding="utf-8") + + def patch_sentencepiece_bpe_null(text: str) -> str: """Preserve legacy BPE NUL IDs only against the audited SentencePiece archive.""" pattern = r'http_archive\(\n name = "sentencepiece",\n.*?\n\)' @@ -641,6 +674,8 @@ def build_runtime( source_root, upstream_tag, spatial_staging=patch_stage_spatial_tensors, cpu_options=patch_cpu_options_identifier, xnnpack=patch_xnnpack, ) + if platform == "windows" and upstream_tag == "v0.20.0": + patch_windows_rules_android(source_root) patch_asr_untimed_overlap(source_root, upstream_tag) patch_asr_litertlm_container(source_root, upstream_tag) patch_stream_finish_reason(source_root, upstream_tag) diff --git a/tools/test_build_upstream_runtime.py b/tools/test_build_upstream_runtime.py index 94168a7..75e7d75 100644 --- a/tools/test_build_upstream_runtime.py +++ b/tools/test_build_upstream_runtime.py @@ -32,6 +32,7 @@ V019_TENSORFLOW_REF, V019_XNNPACK_COMMIT, V019_XNNPACK_SHA256, + V020_TENSORFLOW_REF, declare_patched_xnnpack, ) @@ -373,6 +374,52 @@ def test_workspace_applies_spatial_staging_only_to_the_audited_pin(self) -> None ) self.assertEqual(workspace.read_text(encoding="utf-8"), drift) + def test_windows_v020_uses_a_native_patch_for_tensorflows_android_rules(self) -> None: + call = "tf_workspace2()\n" + original = ( + f'TENSORFLOW_REF = "{V020_TENSORFLOW_REF}"\n' + 'load("@org_tensorflow//tensorflow:workspace2.bzl", "tf_workspace2")\n\n' + + call + ) + with tempfile.TemporaryDirectory() as temp, patch.multiple( + build_upstream_runtime, + verify_carried_dependency_pins=DEFAULT, + patch_asr_untimed_overlap=DEFAULT, + patch_stream_finish_reason=DEFAULT, + patch_huggingface_token_bytes=DEFAULT, + patch_step_zero_state=DEFAULT, + apply_android_gpu_safety=DEFAULT, + materialize_git_lfs_libraries=DEFAULT, + bazel_command=DEFAULT, + prepare_bridge_package=DEFAULT, + fetch_audited_archives=DEFAULT, + run=DEFAULT, + ) as calls: + root = Path(temp) + workspace = root / "WORKSPACE" + calls["bazel_command"].return_value = ["bazel"] + calls["materialize_git_lfs_libraries"].return_value = 0 + calls["prepare_bridge_package"].return_value = [] + calls["run"].side_effect = RuntimeError("Bazel reached") + for platform, tag in (("windows", "v0.20.0"), ("linux", "v0.20.0"), + ("windows", "v0.19.1")): + with self.subTest(platform=platform, tag=tag): + workspace.write_text(original, encoding="utf-8") + for _ in range(2): + with self.assertRaisesRegex(RuntimeError, "Bazel reached"): + build_upstream_runtime.build_runtime(root, platform, "x64", tag, None) + text = workspace.read_text(encoding="utf-8") + if (platform, tag) == ("windows", "v0.20.0"): + name = 'name = "build_bazel_rules_android"' + self.assertEqual(text.count(name), 1) + self.assertLess(text.index(name), text.index(call)) + self.assertIn('patch_args = ["-p1"]', text) + self.assertIn('patches = ["@//bridge:rules_android_tensorflow_v020.patch"]', text) + self.assertIn('sha256 = "af84b69ab3d16dd1a41056286e6511f147a94ccea995603e13e934c915c1631c"', text) + self.assertNotIn("patch_cmds", text) + else: + self.assertEqual(text, original) + def test_source_root_verifies_resolved_archives_before_compilation(self) -> None: workspace = litert_workspace(LITERT_REF, LITERT_ARCHIVE_SHA256) + declare_patched_xnnpack( f'TENSORFLOW_REF = "{V019_TENSORFLOW_REF}"\n' + TENSORFLOW_ARCHIVE + ")\n" From 7cc57b110f15d76bcbbd40e0d716a04c1b7fb451 Mon Sep 17 00:00:00 2001 From: leehack Date: Tue, 24 Nov 2026 03:57:40 -0500 Subject: [PATCH 6/9] Move engine file handle selection outside the status macro --- native/bridge/windows_engine_fd_v020.patch | 29 ++++++++++++ tools/asr_overlap_patch.py | 2 + tools/build_upstream_runtime.py | 9 +++- tools/test_build_upstream_runtime.py | 8 +++- tools/test_v020_decisions.py | 6 +-- tools/windows_engine_fd_patch.py | 55 ++++++++++++++++++++++ 6 files changed, 104 insertions(+), 5 deletions(-) create mode 100644 native/bridge/windows_engine_fd_v020.patch create mode 100644 tools/windows_engine_fd_patch.py diff --git a/native/bridge/windows_engine_fd_v020.patch b/native/bridge/windows_engine_fd_v020.patch new file mode 100644 index 0000000..d6a3cac --- /dev/null +++ b/native/bridge/windows_engine_fd_v020.patch @@ -0,0 +1,29 @@ +diff --git a/c/engine.cc b/c/engine.cc +--- a/c/engine.cc ++++ b/c/engine.cc +@@ -709,17 +709,16 @@ + return litert::lm::c::ReturnError(absl::StatusCode::kInvalidArgument, + "Invalid file descriptor."); + } ++#if defined(_WIN32) ++ const auto platform_file = ++ reinterpret_cast(_get_osfhandle(fd)); ++#else ++ const auto platform_file = fd; ++#endif + LITERT_LM_C_ASSIGN_OR_RETURN( + ModelAssets model_assets, +- ModelAssets::Create( +-#if defined(_WIN32) +- std::make_shared(litert::lm::ScopedFile( +- reinterpret_cast( +- _get_osfhandle(fd)))))); +-#else +- std::make_shared( +- litert::lm::ScopedFile(fd)))); +-#endif ++ ModelAssets::Create(std::make_shared( ++ litert::lm::ScopedFile(platform_file)))); + ABSL_VLOG(1) << "LiteRT-LM successfully created EngineSettings directly " + "from raw File Descriptor: " + << fd; diff --git a/tools/asr_overlap_patch.py b/tools/asr_overlap_patch.py index f6aa8e3..5b3c5f9 100644 --- a/tools/asr_overlap_patch.py +++ b/tools/asr_overlap_patch.py @@ -10,6 +10,7 @@ from litert_stage_spatial_tensors_patch import stage_spatial_tensors_patch_manifest from step_zero_state_patch import manifest as step_zero_state_manifest from stream_finish_reason_patch import finish_reason_patch_manifest +from windows_engine_fd_patch import manifest as windows_engine_fd_manifest from workspace_build_patch import workspace_build_patch_manifest from xnnpack_pf32_sme2_patch import xnnpack_pf32_patch_manifest from xnnpack_pqs8_qc4w_sme2_patch import xnnpack_qc4w_patch_manifest @@ -87,6 +88,7 @@ def source_patch_manifest(compatibility_tag: str) -> list[dict]: return [*overlap, *container_patch_manifest(compatibility_tag), *finish_reason_patch_manifest(compatibility_tag), *android_gpu_safety_manifest(compatibility_tag), + *windows_engine_fd_manifest(compatibility_tag), *workspace_build_patch_manifest(compatibility_tag), *xnnpack_pf32_patch_manifest(compatibility_tag), *xnnpack_qc4w_patch_manifest(compatibility_tag), diff --git a/tools/build_upstream_runtime.py b/tools/build_upstream_runtime.py index ad301df..d2b21b3 100644 --- a/tools/build_upstream_runtime.py +++ b/tools/build_upstream_runtime.py @@ -63,6 +63,10 @@ sources_for as finish_reason_patch_sources, ) from windows_dxc import stage_windows_dxc +from windows_engine_fd_patch import ( + apply as patch_windows_engine_fd, + require_windows_engine_fd_patch_decision, +) import windows_runtime from workspace_build_patch import ( PATCH_PATH as WORKSPACE_BUILD_PATCH_PATH, @@ -681,7 +685,10 @@ def build_runtime( patch_stream_finish_reason(source_root, upstream_tag) patch_huggingface_token_bytes(source_root, upstream_tag) patch_step_zero_state(source_root, upstream_tag) - apply_android_gpu_safety(source_root, upstream_tag) + if platform == "windows" and require_windows_engine_fd_patch_decision(upstream_tag): + patch_windows_engine_fd(source_root, upstream_tag) + else: + apply_android_gpu_safety(source_root, upstream_tag) # v0.19.0 removed the prebuilt TopK sampler this path points at. if (platform == "ios" and has_asr_bridge(upstream_tag) and not is_at_least(upstream_tag, (0, 19, 0))): diff --git a/tools/test_build_upstream_runtime.py b/tools/test_build_upstream_runtime.py index 75e7d75..4d795fc 100644 --- a/tools/test_build_upstream_runtime.py +++ b/tools/test_build_upstream_runtime.py @@ -374,7 +374,7 @@ def test_workspace_applies_spatial_staging_only_to_the_audited_pin(self) -> None ) self.assertEqual(workspace.read_text(encoding="utf-8"), drift) - def test_windows_v020_uses_a_native_patch_for_tensorflows_android_rules(self) -> None: + def test_windows_v020_uses_the_android_rules_and_engine_fd_patches(self) -> None: call = "tf_workspace2()\n" original = ( f'TENSORFLOW_REF = "{V020_TENSORFLOW_REF}"\n' @@ -389,6 +389,7 @@ def test_windows_v020_uses_a_native_patch_for_tensorflows_android_rules(self) -> patch_huggingface_token_bytes=DEFAULT, patch_step_zero_state=DEFAULT, apply_android_gpu_safety=DEFAULT, + patch_windows_engine_fd=DEFAULT, materialize_git_lfs_libraries=DEFAULT, bazel_command=DEFAULT, prepare_bridge_package=DEFAULT, @@ -397,6 +398,7 @@ def test_windows_v020_uses_a_native_patch_for_tensorflows_android_rules(self) -> ) as calls: root = Path(temp) workspace = root / "WORKSPACE" + fd_patch = calls["patch_windows_engine_fd"] calls["bazel_command"].return_value = ["bazel"] calls["materialize_git_lfs_libraries"].return_value = 0 calls["prepare_bridge_package"].return_value = [] @@ -405,11 +407,14 @@ def test_windows_v020_uses_a_native_patch_for_tensorflows_android_rules(self) -> ("windows", "v0.19.1")): with self.subTest(platform=platform, tag=tag): workspace.write_text(original, encoding="utf-8") + fd_patch.reset_mock() for _ in range(2): with self.assertRaisesRegex(RuntimeError, "Bazel reached"): build_upstream_runtime.build_runtime(root, platform, "x64", tag, None) text = workspace.read_text(encoding="utf-8") if (platform, tag) == ("windows", "v0.20.0"): + self.assertEqual([call.args for call in fd_patch.call_args_list], + [(root, tag), (root, tag)]) name = 'name = "build_bazel_rules_android"' self.assertEqual(text.count(name), 1) self.assertLess(text.index(name), text.index(call)) @@ -418,6 +423,7 @@ def test_windows_v020_uses_a_native_patch_for_tensorflows_android_rules(self) -> self.assertIn('sha256 = "af84b69ab3d16dd1a41056286e6511f147a94ccea995603e13e934c915c1631c"', text) self.assertNotIn("patch_cmds", text) else: + fd_patch.assert_not_called() self.assertEqual(text, original) def test_source_root_verifies_resolved_archives_before_compilation(self) -> None: diff --git a/tools/test_v020_decisions.py b/tools/test_v020_decisions.py index 73f2b31..a762741 100644 --- a/tools/test_v020_decisions.py +++ b/tools/test_v020_decisions.py @@ -51,13 +51,13 @@ def test_git_format_carries_apply_inside_owner_checkout(self) -> None: def test_manifest_keeps_audited_carries_with_new_source_identities(self) -> None: previous = source_patch_manifest("v0.19.1") records = source_patch_manifest("v0.20.0") - self.assertEqual({r["id"] for r in records}, {r["id"] for r in previous}) - self.assertEqual(len(records), len(previous) + 1) + self.assertEqual({r["id"] for r in records}, {r["id"] for r in previous} | {"windows-engine-fd"}) + self.assertEqual(len(records), len(previous) + 2) self.assertEqual(len({(r["id"], r["source"]) for r in records}), len(records)) by_id = {r["id"]: r for r in records} for patch_id in ( "android-qwen3-gpu-safety", "huggingface-token-bytes", - "stream-finish-reason", "step-zero-state", "litert-stage-spatial-tensors", + "stream-finish-reason", "step-zero-state", "litert-stage-spatial-tensors", "windows-engine-fd", ): self.assertTrue(by_id[patch_id]["path"].endswith("_v020.patch")) self.assertEqual( diff --git a/tools/windows_engine_fd_patch.py b/tools/windows_engine_fd_patch.py new file mode 100644 index 0000000..e181311 --- /dev/null +++ b/tools/windows_engine_fd_patch.py @@ -0,0 +1,55 @@ +"""Pin the MSVC-compatible engine-settings file descriptor source.""" + +import hashlib +import re +from pathlib import Path + +from android_gpu_safety_patch import V020_SOURCES, apply as apply_android_gpu_safety, digest +from source_patch_utils import apply_source_patch + +PATCH_PATH = "native/bridge/windows_engine_fd_v020.patch" +SOURCE = "c/engine.cc" +PREIMAGE_SHA256 = V020_SOURCES[SOURCE][1] +POSTIMAGE_SHA256 = "c6371431aa7d7d95a2ec0ec1a317be83efd5ae4513f14dd46c51fb0c15816b30" + + +def require_windows_engine_fd_patch_decision(tag: str) -> bool: + if tag == "v0.20.0": + return True + version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", tag) + if version and tuple(map(int, version.groups())) < (0, 20, 0): + return False + raise RuntimeError(f"Windows engine file descriptor patch has no explicit decision for {tag}") + + +def apply(source_root: Path, tag: str) -> None: + if not require_windows_engine_fd_patch_decision(tag): + return + source = source_root / SOURCE + # Both patches touch engine.cc. A retry must also verify the GPU guard's BUILD edit. + if digest(source) == POSTIMAGE_SHA256: + if digest(source_root / "c/BUILD") != V020_SOURCES["c/BUILD"][1]: + raise RuntimeError("C API BUILD source changed; requalify Android GPU preflight") + return + apply_android_gpu_safety(source_root, tag) + if digest(source) != PREIMAGE_SHA256: + raise RuntimeError("Windows engine file descriptor preimage mismatch; requalify") + patch_file = Path(__file__).resolve().parents[1] / PATCH_PATH + apply_source_patch(source_root, patch_file, ignore_space_change=True) + if digest(source) != POSTIMAGE_SHA256: + raise RuntimeError("Windows engine file descriptor postimage mismatch; requalify") + + +def manifest(tag: str) -> list[dict]: + if not require_windows_engine_fd_patch_decision(tag): + return [] + patch_file = Path(__file__).resolve().parents[1] / PATCH_PATH + return [{ + "id": "windows-engine-fd", + "path": PATCH_PATH, + "sha256": hashlib.sha256(patch_file.read_bytes()).hexdigest(), + "source": SOURCE, + "preimageSha256Lf": PREIMAGE_SHA256, + "postimageSha256Lf": POSTIMAGE_SHA256, + "scope": "Windows source-built runtimes only; applies after Android GPU preflight", + }] From 71b29f7c345463f00d4535de131f6c6c0eadce9d Mon Sep 17 00:00:00 2001 From: leehack Date: Tue, 24 Nov 2026 05:17:59 -0500 Subject: [PATCH 7/9] Retire the iOS loader and macOS lookahead carries for LiteRT-LM 0.20 --- CHANGELOG.md | 6 +++ docs/v020_qualification.md | 23 ++++++++--- native/bridge/BUILD.bazel | 1 - .../litert_ios_framework_paths_v020.patch | 13 ------- native/bridge/step_zero_state_v020.patch | 38 ------------------- tools/build_upstream_runtime.py | 6 +-- tools/step_zero_state_patch.py | 31 ++++++--------- tools/test_v020_decisions.py | 9 ++--- 8 files changed, 39 insertions(+), 88 deletions(-) create mode 100644 CHANGELOG.md delete mode 100644 native/bridge/litert_ios_framework_paths_v020.patch delete mode 100644 native/bridge/step_zero_state_v020.patch diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..6c27490 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,6 @@ +# Changelog + +## Unreleased + +- Restore sampler-managed lookahead for macOS linear-attention models after the v0.20.0 CPU and Metal comparison passed. +- Drop the iOS dynamic Metal accelerator path workaround for v0.20.0, whose iOS runtimes link Metal acceleration in-process. diff --git a/docs/v020_qualification.md b/docs/v020_qualification.md index 6fd9858..01c8ada 100644 --- a/docs/v020_qualification.md +++ b/docs/v020_qualification.md @@ -13,16 +13,27 @@ archive identities, Bazel repository tree hashes and patched postimages. | Carry | v0.20.0 decision | | --- | --- | | ASR overlap | Keep the v0.19 patch and pin the new preimage and postimage. The merger's text-utils include moved to `omni/utils`. | -| Stream finish reasons | Rebase onto the shared C API callback helper and the new multi-token decode loop. Keep the finish-reason wire values and bridge ABI. | -| Hugging Face grammar | Rebase on the thread-safe tokenizer and LLGuidance v2. Keep exact ByteLevel bytes, the JSON whitespace bound and depth guard. Preserve upstream SentencePiece byte conversion and multiple EOS IDs. | -| Android Qwen3 preflight | Rebase onto the refactored engine factory. The refusal still runs before factory entry. | -| Step-zero reset and macOS lookahead | Upstream [e1f86b05](https://github.com/google-ai-edge/LiteRT-LM/commit/e1f86b05bf8a731331622a2622440e9f93d9a9f5) supplies state clearing on reset, rewind and a new context. The v0.20 carry contains only the macOS WebGPU linear-attention guard. | +| Stream finish reasons | Keep. The upstream C API callback helper still has no cause field. Stop-token, output-budget and context exhaustion still need to reach the bridge separately. | +| Hugging Face grammar | Keep. Upstream adds SentencePiece byte conversion and multiple EOS IDs. The HF path still reads raw vocabulary spellings without ByteLevel inversion and does not provide the JSON whitespace bound or depth guard. | +| Android Qwen3 preflight | Keep. The refactored upstream C API still enters the engine factory directly, without this model and device refusal. | +| Step-zero reset and macOS lookahead | Retire both. Upstream [e1f86b05](https://github.com/google-ai-edge/LiteRT-LM/commit/e1f86b05bf8a731331622a2622440e9f93d9a9f5) clears state on reset, rewind and a new context. On Apple M4 Max, the pinned Qwen3.5-0.8B and Qwen3-0.6B control both passed the packaged step-zero oracle on CPU and Metal with and without the guard. The unguarded Metal run used sampler-managed inputs and matched the fresh reference in all five repeated Qwen3.5 requests. | | Spatial tensor staging | Rebase the LiteRT WebGPU and Vulkan carry. LiteRT `bf49eb62` predates [aa9e40cd](https://github.com/google-ai-edge/LiteRT/commit/aa9e40cd5e2d892b3a5d8579a7ec6faa696e321e). Retain the pinned LiteRT's per-environment context tracking when staging bindings. | -| XNNPACK PF32 and PQS8/QC4W | Both patches apply in their existing order to the new pin. Update the `gemm-config.c` hashes. | -| iOS Metal framework path | Rebase the legacy path carry. The default build links the accelerator statically. Retiring the path carry still requires packaged iOS evidence. | +| XNNPACK PF32 and PQS8/QC4W | Keep both in order. The pinned XNNPACK archive matches all four PF32 preimages, and its PF32-patched `gemm-config.c` matches the QC4W preimage. The original multi-threaded SME2 triggers remain unqualified without the carries. | +| iOS Metal framework path | Retire the dynamic lookup patch for v0.20.0. The upstream registry tries a statically registered GPU accelerator before dynamic lookup. Both iOS arm64 slices from run [45360694287](https://github.com/leehack/litert-lm-native/actions/runs/45360694287) contain `LiteRtStaticLinkedAcceleratorGpuDef` and `GpuMetalAccelerator::CreateDelegate`, link system Metal, and ship no separate accelerator binary. This verifies the linked path and bundle layout. | | Android Dawn | Keep both checksum-pinned rollback binaries pending Pixel Mali qualification. The validator compares the linked Android runtime's Dawn imports with the final packaged Dawn exports. | | Earlier retired carries | ASR container routing, the v0.18.1 Bazel repair and CPU options identifier rollback stay inactive. The tag retains the upstream SentencePiece patch and initializes GPU environment options before OpenCL. | + +### macOS lookahead retirement evidence + +The four runs used Qwen3.5-0.8B `684d4d34…`, the Qwen3-0.6B attention-only +control `c5f39b41…`, and the maintained fresh-process, reload and cancellation +oracle. Guarded dylib `8949b6bfa927e9530ab6a08b9b07ee13b6e282e378c85b78f565f7d9b06d6597`; +unguarded dylib `13eb2161ef4d6dbf5aee6c78b5a6bcd3e649c298b8954161153c7de183ec6341`. +The Metal logs showed executor-managed inputs with the guard and +sampler-managed inputs without it. The attention-only arithmetic control +passed on both builds and backends. + ## Runtime and consumer contract Source builds still link LiteRT in-process. Upstream removed separate LiteRT diff --git a/native/bridge/BUILD.bazel b/native/bridge/BUILD.bazel index f6c3ae9..2825cae 100644 --- a/native/bridge/BUILD.bazel +++ b/native/bridge/BUILD.bazel @@ -37,7 +37,6 @@ exports_files([ "litert_cpu_options_identifier.patch", "litert_gpu_environment_destroy_callback.patch", "litert_ios_framework_paths.patch", - "litert_ios_framework_paths_v020.patch", "litert_stage_spatial_tensors.patch", "litert_stage_spatial_tensors_v020.patch", "rules_android_tensorflow_v020.patch", diff --git a/native/bridge/litert_ios_framework_paths_v020.patch b/native/bridge/litert_ios_framework_paths_v020.patch deleted file mode 100644 index 83e8d21..0000000 --- a/native/bridge/litert_ios_framework_paths_v020.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/litert/runtime/accelerators/gpu_registry.cc b/litert/runtime/accelerators/gpu_registry.cc ---- a/litert/runtime/accelerators/gpu_registry.cc -+++ b/litert/runtime/accelerators/gpu_registry.cc -@@ -56,7 +56,8 @@ - - #elif TARGET_OS_IPHONE - #if LITERT_HAS_METAL_SUPPORT -- "libLiteRtMetalAccelerator" SO_EXT, -+ "@executable_path/Frameworks/LiteRtMetalAccelerator.framework/" -+ "LiteRtMetalAccelerator", - // Inside an Apple framework bundle the executable is named after the - // bundle, so the accelerator ships as - // LiteRtMetalAccelerator.framework/LiteRtMetalAccelerator. diff --git a/native/bridge/step_zero_state_v020.patch b/native/bridge/step_zero_state_v020.patch deleted file mode 100644 index d624843..0000000 --- a/native/bridge/step_zero_state_v020.patch +++ /dev/null @@ -1,38 +0,0 @@ -diff --git a/runtime/executor/llm_litert_compiled_model_executor.cc b/runtime/executor/llm_litert_compiled_model_executor.cc -index eb57d957..fb15df70 100644 ---- a/runtime/executor/llm_litert_compiled_model_executor.cc -+++ b/runtime/executor/llm_litert_compiled_model_executor.cc -@@ -57,6 +57,7 @@ - #include "litert/cc/litert_tensor_buffer.h" // from @litert - #include "litert/cc/litert_tensor_buffer_types.h" // from @litert - #if defined(__APPLE__) -+#include - #include "litert/cc/options/litert_gpu_options.h" // from @litert - #endif // defined(__APPLE__) - #include "runtime/components/constrained_decoding/constrained_decoder.h" -@@ -1955,6 +1956,25 @@ absl::Status LlmLiteRtCompiledModelExecutorBase::InitializeSampler( - sampler_handles_input = - executor_settings_.GetAdvancedSettings()->sampler_handles_input; - } -+#if defined(__APPLE__) && TARGET_OS_OSX -+ if (sampler_handles_input && sampler_backend == Backend::GPU && -+ executor_settings_.GetBackend() == Backend::GPU && -+ executor_metadata_ != nullptr && -+ executor_metadata_->has_llm_executor_metadata() && -+ absl::c_any_of( -+ executor_metadata_->llm_executor_metadata().state_buffers(), -+ [](const proto::StateBuffer& state) { -+ return state.type() == proto::StateBuffer::TYPE_LINEAR_ATTENTION; -+ })) { -+ const auto options = env_.GetOptions(); -+ if (options.HasValue() && -+ options->GetOption(EnvironmentOptions::Tag::kWebGpuDevice).HasValue()) { -+ sampler_handles_input = false; -+ ABSL_LOG(INFO) << "Using executor-managed decode inputs for WebGPU " -+ "linear attention on macOS."; -+ } -+ } -+#endif - const AttentionMaskParams sampler_attn_params = - GetAttentionMaskParams(executor_metadata_); - const TensorBuffer* decode_attn_mask_buffer = diff --git a/tools/build_upstream_runtime.py b/tools/build_upstream_runtime.py index d2b21b3..a442470 100644 --- a/tools/build_upstream_runtime.py +++ b/tools/build_upstream_runtime.py @@ -494,10 +494,8 @@ def patch_upstream_workspace( else: text = text.replace(needle, replacement) litert_patches = [] - if patch_ios_framework_paths: - litert_patches.append("litert_ios_framework_paths_v020.patch" - if compatibility_tag == "v0.20.0" - else "litert_ios_framework_paths.patch") + if patch_ios_framework_paths and not is_at_least(compatibility_tag, (0, 20, 0)): + litert_patches.append("litert_ios_framework_paths.patch") if patch_gpu_environment_teardown: litert_patches.append("litert_gpu_environment_destroy_callback.patch") if patch_cpu_options_identifier: diff --git a/tools/step_zero_state_patch.py b/tools/step_zero_state_patch.py index de24015..5e6ad75 100644 --- a/tools/step_zero_state_patch.py +++ b/tools/step_zero_state_patch.py @@ -10,19 +10,12 @@ PREIMAGE = "5e6898eb07178719c554ed49e4bc79d891badea4ad0576d00af54ef1bd8dbb4c" POSTIMAGE = "b2c73fbcb400654072bf926dbaa3b81e252acf750f8fc1a60dd0b51df84d890d" -V020_PATCH_PATH = "native/bridge/step_zero_state_v020.patch" -V020_PREIMAGE = "4ccb5ef331ab7d10927d618fee8041cf030500700646efeb2aab0e57c3212c32" -V020_POSTIMAGE = "96ebbe1e0cdbdcfe00407cf6ead2b2df1073ab9eb53695a917bf487da3482e7a" - - -def identity_for(tag: str) -> tuple[str, str, str]: - if tag == "v0.20.0": - return V020_PATCH_PATH, V020_PREIMAGE, V020_POSTIMAGE - return PATCH_PATH, PREIMAGE, POSTIMAGE def applies(tag: str) -> bool: - if tag in {"v0.19.1", "v0.20.0"}: + if tag == "v0.20.0": + return False + if tag == "v0.19.1": return True version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", tag) if version and tuple(map(int, version.groups())) < (0, 19, 1): @@ -38,30 +31,28 @@ def _digest(path: Path) -> str: def apply(source_root: Path, tag: str) -> None: if not applies(tag): return - patch_path, preimage, postimage = identity_for(tag) path = source_root / SOURCE digest = _digest(path) - if digest == postimage: + if digest == POSTIMAGE: return - if digest != preimage: + if digest != PREIMAGE: raise RuntimeError("Executor source changed; requalify the step-zero state patch") - patch = Path(__file__).resolve().parents[1] / patch_path + patch = Path(__file__).resolve().parents[1] / PATCH_PATH apply_source_patch(source_root, patch, ignore_space_change=True) - if _digest(path) != postimage: + if _digest(path) != POSTIMAGE: raise RuntimeError("Executor step-zero state postimage mismatch") def manifest(tag: str) -> list[dict]: if not applies(tag): return [] - patch_path, preimage, postimage = identity_for(tag) - patch = Path(__file__).resolve().parents[1] / patch_path + patch = Path(__file__).resolve().parents[1] / PATCH_PATH return [{ "id": "step-zero-state", - "path": patch_path, + "path": PATCH_PATH, "sha256": hashlib.sha256(patch.read_bytes()).hexdigest(), "source": SOURCE, - "preimageSha256Lf": preimage, - "postimageSha256Lf": postimage, + "preimageSha256Lf": PREIMAGE, + "postimageSha256Lf": POSTIMAGE, "scope": "source-built runtimes only; excludes official upstream prebuilts", }] diff --git a/tools/test_v020_decisions.py b/tools/test_v020_decisions.py index a762741..5648be6 100644 --- a/tools/test_v020_decisions.py +++ b/tools/test_v020_decisions.py @@ -7,7 +7,6 @@ from unittest.mock import patch import android_gpu_safety_patch -import step_zero_state_patch import stream_finish_reason_patch from asr_overlap_patch import source_patch_manifest, source_sha256 from build_upstream_runtime import patch_stream_finish_reason @@ -23,8 +22,6 @@ def test_git_format_carries_apply_inside_owner_checkout(self) -> None: names_and_appliers = ( (stream_finish_reason_patch, "c/c_api_internal.h", patch_stream_finish_reason, {"V020_SOURCES": {"c/c_api_internal.h": hashes}}), - (step_zero_state_patch, step_zero_state_patch.SOURCE, step_zero_state_patch.apply, - {"V020_PREIMAGE": hashes[0], "V020_POSTIMAGE": hashes[1]}), (android_gpu_safety_patch, "c/engine.cc", android_gpu_safety_patch.apply, {"V020_SOURCES": {"c/engine.cc": hashes}}), ) @@ -51,13 +48,13 @@ def test_git_format_carries_apply_inside_owner_checkout(self) -> None: def test_manifest_keeps_audited_carries_with_new_source_identities(self) -> None: previous = source_patch_manifest("v0.19.1") records = source_patch_manifest("v0.20.0") - self.assertEqual({r["id"] for r in records}, {r["id"] for r in previous} | {"windows-engine-fd"}) - self.assertEqual(len(records), len(previous) + 2) + self.assertEqual({r["id"] for r in records}, ({r["id"] for r in previous} - {"step-zero-state"}) | {"windows-engine-fd"}) + self.assertEqual(len(records), len(previous) + 1) self.assertEqual(len({(r["id"], r["source"]) for r in records}), len(records)) by_id = {r["id"]: r for r in records} for patch_id in ( "android-qwen3-gpu-safety", "huggingface-token-bytes", - "stream-finish-reason", "step-zero-state", "litert-stage-spatial-tensors", "windows-engine-fd", + "stream-finish-reason", "litert-stage-spatial-tensors", "windows-engine-fd", ): self.assertTrue(by_id[patch_id]["path"].endswith("_v020.patch")) self.assertEqual( From a006dffc4fcf302eb9089284bee8f06b3fe508e8 Mon Sep 17 00:00:00 2001 From: leehack Date: Tue, 24 Nov 2026 05:33:28 -0500 Subject: [PATCH 8/9] Remove historical LiteRT-LM carries from the current builder --- .github/workflows/native_release.yml | 1 + CHANGELOG.md | 1 + README.md | 4 + docs/asr_untimed_overlap.md | 3 + docs/release_protocol.md | 6 + docs/upstream_patch_audit.md | 3 + docs/v019_qualification.md | 3 + docs/v020_qualification.md | 4 +- native/bridge/BUILD.bazel | 18 - native/bridge/android_gpu_safety_v019.patch | 38 - native/bridge/asr_litertlm_container.patch | 201 ---- native/bridge/asr_untimed_overlap.patch | 109 --- .../bridge/huggingface_token_bytes_v019.patch | 238 ----- .../litert_cpu_options_identifier.patch | 14 - ...ert_gpu_environment_destroy_callback.patch | 23 - .../bridge/litert_ios_framework_paths.patch | 10 - native/bridge/litert_lm_bridge.c | 2 +- .../bridge/litert_stage_spatial_tensors.patch | 254 ----- native/bridge/sentencepiece_bpe_null.patch | 57 -- native/bridge/step_zero_state_v0191.patch | 69 -- .../bridge/step_zero_state_v0191_test.patch | 400 -------- native/bridge/stream_finish_reason.patch | 307 ------ native/bridge/stream_finish_reason_v019.patch | 304 ------ native/bridge/v0181_workspace_build.patch | 107 --- tools/android_gpu_safety_patch.py | 53 +- tools/asr_litertlm_container_patch.py | 62 -- tools/asr_overlap_patch.py | 84 +- tools/build_upstream_runtime.py | 400 ++------ tools/fixtures/asr_engine_v018.cc | 347 ------- tools/fixtures/asr_engine_v018.h | 133 --- .../litert_lm_v0.17.0_workspace_excerpt.txt | 56 -- .../litert_lm_v0.18.0_workspace_excerpt.txt | 59 -- tools/fixtures/litert_lm_v0.18.1.bazelrc | 541 ----------- tools/fixtures/litert_lm_v0.18.1_WORKSPACE | 641 ------------- tools/fixtures/omni_asr_BUILD_v018.txt | 700 -------------- tools/fixtures/timestamp_text_merger_v018.cc | 325 ------- tools/fixtures/timestamp_text_merger_v020.cc | 877 ++++++++++++++++++ tools/gpu_environment_teardown.py | 6 +- tools/huggingface_token_bytes_patch.py | 69 +- tools/litert_cpu_options_identifier_patch.py | 89 -- tools/litert_lm_finish_reason_smoke.py | 6 +- tools/litert_stage_spatial_tensors_patch.py | 60 +- tools/prebuilt_overrides.py | 94 +- tools/qualify_asr_untimed_overlap.py | 23 +- tools/qualify_huggingface_token_bytes.py | 8 +- tools/source_patch_utils.py | 11 + tools/step_zero_state_patch.py | 58 -- tools/stream_finish_reason_patch.py | 104 +-- tools/test_android_gpu_safety.py | 14 +- tools/test_android_protobuf_policy.py | 5 +- tools/test_asr_litertlm_container_patch.py | 125 --- tools/test_asr_untimed_overlap.py | 45 +- tools/test_build_upstream_runtime.py | 431 +-------- tools/test_huggingface_token_bytes_patch.py | 23 +- tools/test_ios_runtime_policy.py | 14 +- ...est_litert_cpu_options_identifier_patch.py | 141 --- tools/test_litert_lm_finish_reason_smoke.py | 12 +- ...test_litert_stage_spatial_tensors_patch.py | 14 +- tools/test_macos_runtime_policy.py | 2 +- tools/test_package_release.py | 27 +- tools/test_package_upstream_prebuilts.py | 12 +- tools/test_prebuilt_overrides.py | 36 +- tools/test_step_zero_state_patch.py | 59 -- tools/test_stream_finish_reason_patch.py | 35 +- tools/test_stream_proxy_callback_abi.py | 8 +- tools/test_v0181_qualification.py | 111 --- tools/test_v019_decisions.py | 170 ---- tools/test_v020_decisions.py | 26 +- tools/test_validate_release_manifest.py | 30 +- tools/test_workspace_build_patch.py | 130 --- tools/test_xnnpack_pf32_sme2_patch.py | 93 +- tools/test_xnnpack_pqs8_qc4w_sme2_patch.py | 20 +- tools/windows_engine_fd_patch.py | 22 +- tools/workspace_build_patch.py | 59 -- tools/xnnpack_pf32_sme2_patch.py | 114 +-- tools/xnnpack_pqs8_qc4w_sme2_patch.py | 50 +- 76 files changed, 1305 insertions(+), 7505 deletions(-) delete mode 100644 native/bridge/android_gpu_safety_v019.patch delete mode 100644 native/bridge/asr_litertlm_container.patch delete mode 100644 native/bridge/asr_untimed_overlap.patch delete mode 100644 native/bridge/huggingface_token_bytes_v019.patch delete mode 100644 native/bridge/litert_cpu_options_identifier.patch delete mode 100644 native/bridge/litert_gpu_environment_destroy_callback.patch delete mode 100644 native/bridge/litert_ios_framework_paths.patch delete mode 100644 native/bridge/litert_stage_spatial_tensors.patch delete mode 100644 native/bridge/sentencepiece_bpe_null.patch delete mode 100644 native/bridge/step_zero_state_v0191.patch delete mode 100644 native/bridge/step_zero_state_v0191_test.patch delete mode 100644 native/bridge/stream_finish_reason.patch delete mode 100644 native/bridge/stream_finish_reason_v019.patch delete mode 100644 native/bridge/v0181_workspace_build.patch delete mode 100644 tools/asr_litertlm_container_patch.py delete mode 100644 tools/fixtures/asr_engine_v018.cc delete mode 100644 tools/fixtures/asr_engine_v018.h delete mode 100644 tools/fixtures/litert_lm_v0.17.0_workspace_excerpt.txt delete mode 100644 tools/fixtures/litert_lm_v0.18.0_workspace_excerpt.txt delete mode 100644 tools/fixtures/litert_lm_v0.18.1.bazelrc delete mode 100644 tools/fixtures/litert_lm_v0.18.1_WORKSPACE delete mode 100644 tools/fixtures/omni_asr_BUILD_v018.txt delete mode 100644 tools/fixtures/timestamp_text_merger_v018.cc create mode 100644 tools/fixtures/timestamp_text_merger_v020.cc delete mode 100644 tools/litert_cpu_options_identifier_patch.py delete mode 100644 tools/step_zero_state_patch.py delete mode 100644 tools/test_asr_litertlm_container_patch.py delete mode 100644 tools/test_litert_cpu_options_identifier_patch.py delete mode 100644 tools/test_step_zero_state_patch.py delete mode 100644 tools/test_v0181_qualification.py delete mode 100644 tools/test_v019_decisions.py delete mode 100644 tools/test_workspace_build_patch.py delete mode 100644 tools/workspace_build_patch.py diff --git a/.github/workflows/native_release.yml b/.github/workflows/native_release.yml index 6c70492..526e243 100644 --- a/.github/workflows/native_release.yml +++ b/.github/workflows/native_release.yml @@ -128,6 +128,7 @@ jobs: set -euo pipefail test "$(git rev-parse HEAD)" = "$NATIVE_COMMIT" test "$GITHUB_SHA" = "$NATIVE_COMMIT" + PYTHONPATH=tools python3 -c 'import sys; from build_upstream_runtime import require_source_build; require_source_build(sys.argv[1])' "$COMPATIBILITY_TAG" if [ -n "${CANDIDATE_SOURCE:-}" ]; then test "$PUBLICATION_APPROVAL" = publish PYTHONPATH=tools python3 -c 'import os; from candidate_promotion import parse_source; parse_source(os.environ["CANDIDATE_SOURCE"])' diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c27490..8a35686 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,3 +4,4 @@ - Restore sampler-managed lookahead for macOS linear-attention models after the v0.20.0 CPU and Metal comparison passed. - Drop the iOS dynamic Metal accelerator path workaround for v0.20.0, whose iOS runtimes link Metal acceleration in-process. +- Use the recorded native release refs to reproduce builds before LiteRT-LM v0.20.0. diff --git a/README.md b/README.md index a698420..89282cc 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,10 @@ Development builds use `g` and development rebuilds append the same compact `-N`. Historical `-native.N` releases remain immutable and consumable but are never emitted again. +The current source builder qualifies LiteRT-LM v0.20.0. Reproduce an older +release from its native tag and use the tooling at that ref. The released +archives and metadata remain available for existing consumers. + When moving to a new LiteRT-LM tag: 1. Let `Detect Upstream Release` prepare exact inputs, or resolve the exact diff --git a/docs/asr_untimed_overlap.md b/docs/asr_untimed_overlap.md index e1c4093..0b29d69 100644 --- a/docs/asr_untimed_overlap.md +++ b/docs/asr_untimed_overlap.md @@ -1,5 +1,8 @@ # Untimed ASR overlap qualification (#673) +The current v0.20.0 builder uses the port below with v0.20.0 source hashes. +The v0.18 and v0.19 rebuild instructions refer to their native release refs. + ## v0.19.0 port v0.19.0 moved the merger to `omni/speech2text` and replaced the word-count diff --git a/docs/release_protocol.md b/docs/release_protocol.md index 30c6672..8ef3260 100644 --- a/docs/release_protocol.md +++ b/docs/release_protocol.md @@ -61,6 +61,12 @@ and immediate lower same-line predecessor, reuse or decrease of a rebuild number legacy output forms, partial publication matrices, and publication without the required real-model smoke evidence. +Source builds at the current ref use the v0.20.0 compatibility baseline. +For an older release, use the recorded native commit and its workflow ref +for reproduction, including validation of historical source patch records. +The released assets and the frozen legacy metadata fixtures retain their +original provenance. + Stable manual preflight applies the same consumability decision as upstream detection before any of the eight platform builds start. A metadata-only tag at an already packaged commit is rejected unless the requested native identity is diff --git a/docs/upstream_patch_audit.md b/docs/upstream_patch_audit.md index dedc3ad..8c27910 100644 --- a/docs/upstream_patch_audit.md +++ b/docs/upstream_patch_audit.md @@ -1,5 +1,8 @@ # LiteRT-LM v0.18.0 carried-fix audit +This is a historical record. The pre-v0.20.0 patch files and build commands +below belong to their native release refs. + For later baselines, see [v0.19 qualification](v019_qualification.md) and [v0.20 qualification](v020_qualification.md). Android C API 1.0 also has an owner [protobuf link-isolation policy](android_protobuf_isolation.md); diff --git a/docs/v019_qualification.md b/docs/v019_qualification.md index 31a2836..2449b27 100644 --- a/docs/v019_qualification.md +++ b/docs/v019_qualification.md @@ -1,5 +1,8 @@ # LiteRT-LM v0.19.0 owner qualification +This historical qualification uses the files and tools at the v0.19 native +release refs. See [v0.20 qualification](v020_qualification.md) for current carries. + Upstream tag `v0.19.0` is `83ce6067f2e2a3fb697556928f93936693ded971` (LiteRT `dcb657e8`, TensorFlow `4f8e6d47`, XNNPACK `28d1fc6d`). Issue [#75](https://github.com/leehack/litert-lm-native/issues/75) was written against diff --git a/docs/v020_qualification.md b/docs/v020_qualification.md index 01c8ada..a186215 100644 --- a/docs/v020_qualification.md +++ b/docs/v020_qualification.md @@ -21,7 +21,9 @@ archive identities, Bazel repository tree hashes and patched postimages. | XNNPACK PF32 and PQS8/QC4W | Keep both in order. The pinned XNNPACK archive matches all four PF32 preimages, and its PF32-patched `gemm-config.c` matches the QC4W preimage. The original multi-threaded SME2 triggers remain unqualified without the carries. | | iOS Metal framework path | Retire the dynamic lookup patch for v0.20.0. The upstream registry tries a statically registered GPU accelerator before dynamic lookup. Both iOS arm64 slices from run [45360694287](https://github.com/leehack/litert-lm-native/actions/runs/45360694287) contain `LiteRtStaticLinkedAcceleratorGpuDef` and `GpuMetalAccelerator::CreateDelegate`, link system Metal, and ship no separate accelerator binary. This verifies the linked path and bundle layout. | | Android Dawn | Keep both checksum-pinned rollback binaries pending Pixel Mali qualification. The validator compares the linked Android runtime's Dawn imports with the final packaged Dawn exports. | -| Earlier retired carries | ASR container routing, the v0.18.1 Bazel repair and CPU options identifier rollback stay inactive. The tag retains the upstream SentencePiece patch and initializes GPU environment options before OpenCL. | +| Windows Android rules repository | Keep. TensorFlow still invokes Bash and `sed` for four repository edits. The native Bazel patch produces the same four files from the pinned archive. | +| Windows C API file descriptor | Keep. The pinned `c/engine.cc` still has a directive inside a macro argument. The carry selects the platform handle before invoking the macro. | +| Earlier retired carries | ASR container routing, the v0.18.1 Bazel repair and CPU options identifier rollback were removed from the current builder. The tag retains the upstream SentencePiece patch and initializes GPU environment options before OpenCL. Historical builds use their recorded native release refs. | ### macOS lookahead retirement evidence diff --git a/native/bridge/BUILD.bazel b/native/bridge/BUILD.bazel index 2825cae..5dd1660 100644 --- a/native/bridge/BUILD.bazel +++ b/native/bridge/BUILD.bazel @@ -31,18 +31,9 @@ cc_library( ) exports_files([ - "asr_untimed_overlap.patch", - "huggingface_token_bytes_v019.patch", "asr_untimed_overlap_v019.patch", - "litert_cpu_options_identifier.patch", - "litert_gpu_environment_destroy_callback.patch", - "litert_ios_framework_paths.patch", - "litert_stage_spatial_tensors.patch", "litert_stage_spatial_tensors_v020.patch", "rules_android_tensorflow_v020.patch", - "sentencepiece_bpe_null.patch", - "stream_finish_reason.patch", - "stream_finish_reason_v019.patch", "xnnpack_pf32_sme2.patch", "xnnpack_pqs8_qc4w_sme2.patch", ]) @@ -52,7 +43,6 @@ config_setting( define_values = {"litert_lm_stream_chunk_api": "true"}, ) -# Set only when stream_finish_reason.patch is applied to the upstream source. config_setting( name = "finish_reason_api", define_values = {"litert_lm_finish_reason_api": "true"}, @@ -93,13 +83,6 @@ config_setting( ) # The combined Android accelerator can select either sampler at runtime. -config_setting( - name = "android_webgpu_sampler", - constraint_values = ["@platforms//os:android"], - define_values = {"litert_lm_android_webgpu_sampler": "true"}, -) - -# v0.17 moved the capabilities C implementation into //c:engine. config_setting( name = "android_opencl_sampler", constraint_values = ["@platforms//os:android"], @@ -295,7 +278,6 @@ cc_binary( ":litert_lm_asr_bridge", "//c:engine", ] + CAPABILITIES_DEPS + select({ - ":android_webgpu_sampler": ["//runtime/components:top_k_webgpu_sampler_static"], ":android_opencl_sampler": ["//runtime/components:top_k_opencl_sampler_static"], "//conditions:default": [], }), diff --git a/native/bridge/android_gpu_safety_v019.patch b/native/bridge/android_gpu_safety_v019.patch deleted file mode 100644 index aa30a6b..0000000 --- a/native/bridge/android_gpu_safety_v019.patch +++ /dev/null @@ -1,38 +0,0 @@ ---- a/c/engine.cc -+++ b/c/engine.cc -@@ -13,6 +13,7 @@ - // limitations under the License. - - #include "c/engine.h" -+#include "bridge/litert_lm_android_gpu_preflight.h" - - #include - #include -@@ -1117,8 +1118,16 @@ - "Invalid engine settings."); - } - -+#if defined(__ANDROID__) -+ auto guarded_settings = *settings->settings; -+ const auto safety = litert_lm_native::PrepareAndroidGpuSafety(guarded_settings); -+ if (!safety.ok()) return litert::lm::c::ToCStatus(safety); -+ const auto& selected_settings = guarded_settings; -+#else -+ const auto& selected_settings = *settings->settings; -+#endif - absl::StatusOr> engine = -- EngineFactory::CreateDefault(*settings->settings); -+ EngineFactory::CreateDefault(selected_settings); - - if (!engine.ok()) { - ABSL_LOG(ERROR) << "Failed to create engine: " << engine.status(); ---- a/c/BUILD -+++ b/c/BUILD -@@ -43,6 +43,7 @@ - ]) - - ENGINE_LITE_COMMON_DEPS = [ -+ "//bridge:litert_lm_android_gpu_preflight", - ":engine_internal", - ":error_reporter_headers", - ":error_reporter_internal", diff --git a/native/bridge/asr_litertlm_container.patch b/native/bridge/asr_litertlm_container.patch deleted file mode 100644 index fbc8f07..0000000 --- a/native/bridge/asr_litertlm_container.patch +++ /dev/null @@ -1,201 +0,0 @@ ---- a/omni/asr/BUILD -+++ b/omni/asr/BUILD -@@ -600,6 +600,8 @@ cc_library( - "//runtime/components:model_resources", - "//runtime/executor:executor_settings_base", - "//runtime/framework:threadpool", -+ "//runtime/proto:asr_metadata_cc_proto", -+ "//runtime/proto:asr_model_type_cc_proto", - "//support/tokenizer", - "//support/tokenizer:huggingface_tokenizer", - ], ---- a/omni/asr/asr_engine.cc -+++ b/omni/asr/asr_engine.cc -@@ -59,6 +59,8 @@ - #include "runtime/components/model_resources.h" - #include "runtime/executor/executor_settings_base.h" - #include "runtime/framework/threadpool.h" -+#include "runtime/proto/asr_metadata.pb.h" -+#include "runtime/proto/asr_model_type.pb.h" - #include "support/tokenizer/huggingface_tokenizer.h" - #include "support/tokenizer/tokenizer.h" - -@@ -74,6 +76,44 @@ bool FileExists(absl::string_view path) { - return f.good(); - } - -+void ResolveDecoderTypeFromLitertLm(lm::ModelResources& lm_resources, -+ AsrEngineConfig& config) { -+ auto asr_metadata = lm_resources.GetAsrMetadata(); -+ if (asr_metadata.ok() && *asr_metadata != nullptr) { -+ switch ((*asr_metadata)->asr_model_type().model_type_case()) { -+ case lm::proto::AsrModelType::kWhisper: -+ case lm::proto::AsrModelType::kMoonshine: -+ config.decoder_type = AsrEngineConfig::DecoderType::kStateless; -+ return; -+ case lm::proto::AsrModelType::kParakeet: -+ if (lm_resources -+ .GetTFLiteModelBuffer( -+ lm::proto::AsrMetadata::TF_LITE_ENCODER_DECODER) -+ .ok()) { -+ config.decoder_type = AsrEngineConfig::DecoderType::kTdt; -+ } else if (lm_resources -+ .GetTFLiteModelBuffer( -+ lm::proto::AsrMetadata::TF_LITE_AUDIO_ENCODER) -+ .ok()) { -+ config.decoder_type = AsrEngineConfig::DecoderType::kCtc; -+ } -+ return; -+ case lm::proto::AsrModelType::kQwen3Asr: -+ config.decoder_type = AsrEngineConfig::DecoderType::kLm; -+ return; -+ case lm::proto::AsrModelType::MODEL_TYPE_NOT_SET: -+ break; -+ } -+ } -+ // Legacy LLM-based ASR .litertlm packages (e.g., tinygemma-asr, -+ // qwen3-asr-0.6b) may only contain LlmMetadata without an AsrMetadata -+ // section, so check for LlmMetadata as a fallback to identify LM decoders. -+ auto llm_metadata = lm_resources.GetLlmMetadata(); -+ if (llm_metadata.ok() && *llm_metadata != nullptr) { -+ config.decoder_type = AsrEngineConfig::DecoderType::kLm; -+ } -+} -+ - } // namespace - - absl::Status AsrEngine::EnsureFilesDownloaded( -@@ -134,30 +174,59 @@ absl::StatusOr> AsrEngine::Create( - auto thread_pool = std::make_unique<::litert::lm::ThreadPool>( - "asr_engine_pool", config.num_threads); - -- bool use_litert_lm = -- config.decoder_type == AsrEngineConfig::DecoderType::kLm || -- absl::EndsWith(config.model_path, ".litertlm"); -- if (!use_litert_lm) { -- ABSL_ASSIGN_OR_RETURN( -- auto tokenizer, ::litert::support::HuggingFaceTokenizer::CreateFromFile( -- config.tokenizer_path)); -+ std::shared_ptr lm_resources; -+ if (absl::EndsWith(config.model_path, ".litertlm")) { -+ ABSL_ASSIGN_OR_RETURN(lm_resources, -+ CreateLmModelResources(config.model_path)); -+ ResolveDecoderTypeFromLitertLm(*lm_resources, config); -+ } -+ -+ if (config.decoder_type != AsrEngineConfig::DecoderType::kLm) { -+ std::unique_ptr<::litert::support::Tokenizer> tokenizer; -+ std::unique_ptr<::litert::CompiledModel> compiled_model; -+ -+ if (lm_resources != nullptr) { -+ ABSL_ASSIGN_OR_RETURN(tokenizer, lm_resources->GetTokenizer()); -+ auto model_buffer = lm_resources->GetTFLiteModelBuffer( -+ lm::proto::AsrMetadata::TF_LITE_ENCODER_DECODER); -+ if (!model_buffer.ok()) { -+ model_buffer = lm_resources->GetTFLiteModelBuffer( -+ lm::proto::AsrMetadata::TF_LITE_AUDIO_ENCODER); -+ } -+ if (!model_buffer.ok()) { -+ return model_buffer.status(); -+ } -+ LITERT_ASSIGN_OR_RETURN( -+ auto comp_model, -+ ::litert::CompiledModel::Create( -+ environment, -+ ::litert::BufferRef( -+ reinterpret_cast(model_buffer->data()), -+ model_buffer->size()), -+ options)); -+ compiled_model = -+ std::make_unique<::litert::CompiledModel>(std::move(comp_model)); -+ } else { -+ ABSL_ASSIGN_OR_RETURN( -+ tokenizer, ::litert::support::HuggingFaceTokenizer::CreateFromFile( -+ config.tokenizer_path)); -+ LITERT_ASSIGN_OR_RETURN(auto comp_model, -+ ::litert::CompiledModel::Create( -+ environment, config.model_path, options)); -+ compiled_model = -+ std::make_unique<::litert::CompiledModel>(std::move(comp_model)); -+ } -+ - if (config.vocab_size == 0) { - config.vocab_size = tokenizer->GetVocabSize(); - } - -- LITERT_ASSIGN_OR_RETURN(auto compiled_model, -- ::litert::CompiledModel::Create( -- environment, config.model_path, options)); -- - return std::unique_ptr(new AsrEngine( -- std::move(config), std::move(tokenizer), -+ std::move(config), std::move(lm_resources), std::move(tokenizer), - std::make_unique<::litert::Environment>(std::move(environment)), -- std::make_unique<::litert::CompiledModel>(std::move(compiled_model)), -- std::move(thread_pool))); -+ std::move(compiled_model), std::move(thread_pool))); - } - -- config.decoder_type = AsrEngineConfig::DecoderType::kLm; -- - ModelOptions lm_options; - if (config.backend == AsrEngineConfig::Backend::kGpu) { - lm_options.backend = lm::Backend::GPU; -@@ -222,20 +291,23 @@ absl::StatusOr> AsrEngine::Create( - } - - return std::unique_ptr(new AsrEngine( -- std::move(config), std::move(tokenizer), -+ std::move(config), std::move(lm_resources), std::move(tokenizer), - std::make_unique<::litert::Environment>(std::move(environment)), - std::move(compiled_model), std::move(thread_pool), std::move(lm_runner), - std::move(lm_engine_runner))); - } - --AsrEngine::AsrEngine(AsrEngineConfig config, -- std::unique_ptr<::litert::support::Tokenizer> tokenizer, -- std::unique_ptr<::litert::Environment> environment, -- std::unique_ptr<::litert::CompiledModel> compiled_model, -- std::unique_ptr<::litert::lm::ThreadPool> thread_pool, -- std::unique_ptr lm_runner, -- std::unique_ptr lm_engine_runner) -+AsrEngine::AsrEngine( -+ AsrEngineConfig config, -+ std::shared_ptr<::litert::lm::ModelResources> model_resources, -+ std::unique_ptr<::litert::support::Tokenizer> tokenizer, -+ std::unique_ptr<::litert::Environment> environment, -+ std::unique_ptr<::litert::CompiledModel> compiled_model, -+ std::unique_ptr<::litert::lm::ThreadPool> thread_pool, -+ std::unique_ptr lm_runner, -+ std::unique_ptr lm_engine_runner) - : config_(std::move(config)), -+ model_resources_(std::move(model_resources)), - tokenizer_(std::move(tokenizer)), - environment_(std::move(environment)), - compiled_model_(std::move(compiled_model)), ---- a/omni/asr/asr_engine.h -+++ b/omni/asr/asr_engine.h -@@ -29,6 +29,7 @@ - #include "omni/asr/log_mel_spectrogram_processor.h" - #include "omni/base/litert_lm_engine_runner.h" - #include "omni/base/litert_lm_runner.h" -+#include "runtime/components/model_resources.h" - #include "runtime/framework/threadpool.h" - #include "support/tokenizer/tokenizer.h" - -@@ -109,6 +110,7 @@ class AsrEngine { - - private: - AsrEngine(AsrEngineConfig config, -+ std::shared_ptr<::litert::lm::ModelResources> model_resources, - std::unique_ptr<::litert::support::Tokenizer> tokenizer, - std::unique_ptr<::litert::Environment> environment, - std::unique_ptr<::litert::CompiledModel> compiled_model, -@@ -120,6 +122,7 @@ class AsrEngine { - const FileDownloader& downloader); - - AsrEngineConfig config_; -+ std::shared_ptr<::litert::lm::ModelResources> model_resources_; - std::unique_ptr<::litert::support::Tokenizer> tokenizer_; - std::unique_ptr<::litert::Environment> environment_; - std::unique_ptr<::litert::CompiledModel> compiled_model_; diff --git a/native/bridge/asr_untimed_overlap.patch b/native/bridge/asr_untimed_overlap.patch deleted file mode 100644 index 62ccf72..0000000 --- a/native/bridge/asr_untimed_overlap.patch +++ /dev/null @@ -1,109 +0,0 @@ ---- a/omni/asr/timestamp_text_merger.cc -+++ b/omni/asr/timestamp_text_merger.cc -@@ -207,6 +207,106 @@ - return absl::OkStatus(); - } - -+ // Untimed decoders can garble a cut word at either window edge. Align an -+ // exact canonical suffix/prefix (at least two words), allowing one trailing -+ // word from the old window and two leading words from the new one to differ. -+ // Prefer the longest evidence; ties keep the least trimmed/skipped candidate. -+ // Keep the old spelling of the overlap and the new continuation, without -+ // DedupWords: repeated words after the anchor are legitimate new content. -+ // No reliable anchor: retain the existing fallback. Timed words never enter. -+ if (prev_timestamps_.empty() && curr_timestamps.empty()) { -+ auto prev = CanonicalizeWords(prev_words_); -+ auto curr = CanonicalizeWords(curr_words); -+ const int min_anchor_words = 2; -+ int best_length = min_anchor_words - 1; -+ int best_start = -1, best_skip = 0, best_end = 0; -+ std::optional alignment; -+ bool ambiguous = false; -+ for (int trim = 0; trim <= 1; ++trim) { -+ int end = static_cast(prev.size()) - trim; -+ for (int skip = 0; skip <= 2; ++skip) { -+ for (int start = 0; start < end; ++start) { -+ int length = end - start; -+ if (length < min_anchor_words || -+ skip + length > static_cast(curr.size())) -+ continue; -+ if (!prev[start].empty() && -+ std::equal(prev.begin() + start, prev.begin() + end, -+ curr.begin() + skip)) { -+ if (alignment.has_value() && *alignment != start - skip) ambiguous = true; -+ alignment = start - skip; -+ if (length <= best_length) continue; -+ best_length = length; -+ best_start = start; -+ best_skip = skip; -+ best_end = end; -+ } -+ } -+ } -+ } -+ // A repeated anchor cannot locate the acoustic overlap. In particular, -+ // periodic speech must use the upstream word-count progression. -+ if (best_start >= 0) { -+ for (const auto* words : {&prev, &curr}) { -+ int matches = 0; -+ for (int i = 0; i + best_length <= static_cast(words->size()); ++i) { -+ if (std::equal(prev.begin() + best_start, -+ prev.begin() + best_end, words->begin() + i)) ++matches; -+ } -+ if (matches != 1) ambiguous = true; -+ } -+ } -+ // Short tolerant matches are particularly easy to confuse with a refrain. -+ if ((best_skip || best_end != static_cast(prev.size())) && -+ best_length < 3) ambiguous = true; -+ // Low lexical diversity cannot distinguish an acoustic overlap from a -+ // chant. These conservative confidence cutoffs deliberately trade recall -+ // for the upstream fallback; they are not a proof of text-only alignment. -+ for (const auto* words : {&prev, &curr}) { -+ int distinct = 0; -+ for (int i = 0; i < static_cast(words->size()); ++i) { -+ if (std::find(words->begin(), words->begin() + i, (*words)[i]) == -+ words->begin() + i) ++distinct; -+ } -+ if (distinct < 6 || distinct * 2 <= static_cast(words->size())) -+ ambiguous = true; -+ int repeated = 0; -+ for (int i = 0; i + 1 < static_cast(words->size()); ++i) { -+ int matches = 0; -+ for (int j = 0; j + 1 < static_cast(words->size()); ++j) { -+ if ((*words)[i] == (*words)[j] && -+ (*words)[i + 1] == (*words)[j + 1]) ++matches; -+ } -+ if (matches > 1) ++repeated; -+ } -+ if (repeated > 0 && best_length < 3) ambiguous = true; -+ if (repeated * 2 >= static_cast(words->size())) ambiguous = true; -+ } -+ if (best_start >= 0) { -+ for (int i = 0; i < best_skip; ++i) { -+ if (std::find(prev.begin(), prev.end(), curr[i]) != prev.end()) -+ ambiguous = true; -+ } -+ for (int i = best_end; i < static_cast(prev.size()); ++i) { -+ if (std::find(curr.begin(), curr.end(), prev[i]) != curr.end()) -+ ambiguous = true; -+ } -+ } -+ int earliest = std::max(1, static_cast( -+ prev.size() * (1 - overlap_ratio_)) - search_window_); -+ if (best_start >= earliest && !ambiguous) { -+ std::vector merged(prev_words_.begin() + best_start, -+ prev_words_.begin() + best_end); -+ merged.insert(merged.end(), curr_words.begin() + best_skip + best_length, -+ curr_words.end()); -+ std::string confirmed = absl::StrJoin( -+ absl::MakeSpan(prev_words_).subspan(0, best_start), " "); -+ prev_words_ = std::move(merged); -+ LogAndPushOutput({confirmed, absl::StrJoin(prev_words_, " ")}); -+ return absl::OkStatus(); -+ } -+ } -+ - int middle_index_to_search = 0; - if (!prev_timestamps_.empty() && !curr_timestamps.empty() && - (prev_timestamps_.back() > prev_timestamps_.front() || diff --git a/native/bridge/huggingface_token_bytes_v019.patch b/native/bridge/huggingface_token_bytes_v019.patch deleted file mode 100644 index 3a19bcd..0000000 --- a/native/bridge/huggingface_token_bytes_v019.patch +++ /dev/null @@ -1,238 +0,0 @@ ---- a/support/tokenizer/tokenizer.h -+++ b/support/tokenizer/tokenizer.h -@@ -80,6 +80,17 @@ - // Returns the list of tokens in the tokenizer. - virtual std::vector GetTokens() const = 0; - -+ // Returns llguidance vocabulary entries in token-ID order. Byte-level -+ // tokenizers override this with lossless bytes, including NUL and partial -+ // UTF-8. Legacy providers retain their existing raw-token mapping. -+ virtual absl::StatusOr> GetTokenBytes() const { -+ return GetTokens(); -+ } -+ -+ // Identifies tokenizer-declared control tokens by ID, independently of their -+ // spelling. Constraint-provider configuration can declare more special tokens. -+ virtual bool IsSpecialToken(int) const { return false; } -+ - // Returns the size of the vocabulary. - virtual int GetVocabSize() const = 0; - ---- a/support/tokenizer/huggingface_tokenizer.h -+++ b/support/tokenizer/huggingface_tokenizer.h -@@ -25,6 +25,7 @@ - #include "absl/strings/string_view.h" // from @com_google_absl - #include "absl/types/span.h" // from @com_google_absl - #include "support/tokenizer/tokenizer.h" -+#include "bridge/huggingface_token_bytes.h" - - namespace litert::support { - -@@ -62,15 +63,23 @@ - - std::vector GetTokens() const override; - -+ absl::StatusOr> GetTokenBytes() const override; -+ -+ bool IsSpecialToken(int token_id) const override { -+ return token_bytes_.IsSpecialToken(token_id); -+ } -+ - int GetVocabSize() const override; - - private: - // Constructor. -- explicit HuggingFaceTokenizer(TokenizerHandle absl_nonnull handle) -- : handle_(handle) {}; -+ explicit HuggingFaceTokenizer(TokenizerHandle absl_nonnull handle, -+ const std::string& json) -+ : handle_(handle), token_bytes_(json) {}; - - // HuggingFace processor. - TokenizerHandle absl_nonnull handle_; -+ HuggingFaceTokenBytes token_bytes_; - }; - - } // namespace litert::support ---- a/support/tokenizer/huggingface_tokenizer.cc -+++ b/support/tokenizer/huggingface_tokenizer.cc -@@ -51,7 +51,7 @@ - if (!handle) { - return absl::InvalidArgumentError("Failed to create tokenizer from JSON."); - } -- return absl::WrapUnique(new HuggingFaceTokenizer(handle)); -+ return absl::WrapUnique(new HuggingFaceTokenizer(handle, json)); - } - - // Encodes the given text into a TensorBuffer of token ids. -@@ -107,6 +107,19 @@ - return tokens; - } - -+absl::StatusOr> HuggingFaceTokenizer::GetTokenBytes() const { -+ if (!token_bytes_.supported()) { -+ return absl::UnimplementedError( -+ "HuggingFace constrained decoding requires a ByteLevel decoder; " -+ "this tokenizer decoder has no lossless token-byte adapter."); -+ } -+ auto tokens = GetTokens(); -+ for (size_t id = 0; id < tokens.size(); ++id) { -+ tokens[id] = token_bytes_.TokenBytes(tokens[id], id); -+ } -+ return tokens; -+} -+ - int HuggingFaceTokenizer::GetVocabSize() const { - size_t size = 0; - tokenizers_get_vocab_size(handle_, &size); ---- a/support/tokenizer/BUILD -+++ b/support/tokenizer/BUILD -@@ -97,6 +97,7 @@ - hdrs = ["huggingface_tokenizer.h"], - linkstatic = 1, - deps = [ -+ "//bridge:huggingface_token_bytes", - ":tokenizer", - "@com_google_absl//absl/base:core_headers", - "@com_google_absl//absl/base:nullability", -@@ -114,6 +115,7 @@ - defines = ["ENABLE_HUGGINGFACE_TOKENIZER"], - linkstatic = 1, - deps = [ -+ "//bridge:huggingface_token_bytes", - ":tokenizer", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/debugging:leak_check", # See b/402708346 ---- a/runtime/components/constrained_decoding/llg_constraint_provider.cc -+++ b/runtime/components/constrained_decoding/llg_constraint_provider.cc -@@ -35,9 +35,56 @@ - #include "runtime/components/constrained_decoding/llg_constraint.h" - #include "runtime/components/constrained_decoding/llg_constraint_config.h" - #include "llguidance.h" -+#include "nlohmann/json.hpp" // from @nlohmann_json - - namespace litert::lm { - namespace { -+ -+bool JsonNestingWithinPreprocessingLimit(absl::string_view text) { -+ constexpr size_t kMaxDepth = 128; -+ size_t depth = 0; -+ bool in_string = false; -+ bool escaped = false; -+ for (const char ch : text) { -+ if (in_string) { -+ if (escaped) escaped = false; -+ else if (ch == '\\') escaped = true; -+ else if (ch == '"') in_string = false; -+ } else if (ch == '"') { -+ in_string = true; -+ } else if (ch == '{' || ch == '[') { -+ if (++depth > kMaxDepth) return false; -+ } else if (ch == '}' || ch == ']') { -+ if (depth == 0) return false; -+ --depth; -+ } -+ } -+ return true; -+} -+ -+std::string WithDefaultJsonWhitespace(absl::string_view text) { -+ // Deep DOM insertion/serialization/destruction can exhaust the C++ stack. -+ // Let llguidance validate overdeep input unchanged before building a DOM. -+ if (!JsonNestingWithinPreprocessingLimit(text)) return std::string(text); -+ auto schema = nlohmann::ordered_json::parse(text.begin(), text.end(), nullptr, -+ false); -+ if (schema.is_boolean()) { -+ schema = nlohmann::ordered_json{{"allOf", {schema}}}; -+ } -+ if (!schema.is_object()) return std::string(text); -+ if (!schema.contains("x-guidance")) { -+ schema["x-guidance"] = nlohmann::ordered_json::object(); -+ } -+ auto& options = schema["x-guidance"]; -+ if (!options.is_object() || options.contains("whitespace_pattern") || -+ options.contains("whitespace_flexible")) { -+ return std::string(text); -+ } -+ // An unlimited skip lets greedy decoding spend the entire output budget on -+ // insignificant whitespace. The once-per-gap bound preserves JSON values. -+ options["whitespace_pattern"] = R"([\x20\x0A\x0D\x09]{1,8})"; -+ return schema.dump(); -+} - - ::LlgConstraint* CreateLlgConstraint(LlgConstraintInit* llg_constraint_init, - absl::string_view constraint_string, -@@ -46,9 +93,10 @@ - case LlgConstraintType::kRegex: - return llg_new_constraint_regex(llg_constraint_init, - constraint_string.data()); -- case LlgConstraintType::kJsonSchema: -- return llg_new_constraint_json(llg_constraint_init, -- constraint_string.data()); -+ case LlgConstraintType::kJsonSchema: { -+ const std::string schema = WithDefaultJsonWhitespace(constraint_string); -+ return llg_new_constraint_json(llg_constraint_init, schema.c_str()); -+ } - case LlgConstraintType::kLark: - return llg_new_constraint_lark(llg_constraint_init, - constraint_string.data()); -@@ -67,7 +115,13 @@ - return absl::InvalidArgumentError("LlGuidanceConfig::eos_id must be set."); - } - -- std::vector tokens = tokenizer.GetTokens(); -+ const auto raw_tokens = tokenizer.GetTokens(); -+ auto token_bytes_or = tokenizer.GetTokenBytes(); -+ if (!token_bytes_or.ok()) return token_bytes_or.status(); -+ const auto& tokens = *token_bytes_or; -+ if (tokens.size() != raw_tokens.size()) { -+ return absl::InvalidArgumentError("Token bytes must preserve vocabulary IDs."); -+ } - - absl::flat_hash_set special_tokens_set( - llg_config.special_tokens.begin(), llg_config.special_tokens.end()); -@@ -77,15 +131,19 @@ - size_t total_size = 0; - - token_lens.reserve(tokens.size()); -- for (const auto& token : tokens) { -- bool is_special = special_tokens_set.contains(token); -+ for (size_t id = 0; id < tokens.size(); ++id) { -+ bool is_special = tokenizer.IsSpecialToken(id) || -+ special_tokens_set.contains(raw_tokens[id]); -+ const auto& token = is_special ? raw_tokens[id] : tokens[id]; - token_lens.push_back(token.size() + (is_special ? 1 : 0)); - total_size += token.size() + (is_special ? 1 : 0); - } - - token_bytes.reserve(total_size); -- for (const auto& token : tokens) { -- bool is_special = special_tokens_set.contains(token); -+ for (size_t id = 0; id < tokens.size(); ++id) { -+ bool is_special = tokenizer.IsSpecialToken(id) || -+ special_tokens_set.contains(raw_tokens[id]); -+ const auto& token = is_special ? raw_tokens[id] : tokens[id]; - if (is_special) { - // Special tokens need to be prefixed with 0xFF. - // https://github.com/guidance-ai/llguidance/blob/main/docs/special_tokens.md -@@ -119,7 +177,9 @@ - .tok_eos = *llg_config.eos_id, - .token_lens = token_lens.data(), - .token_bytes = token_bytes.data(), -- .tokenize_assumes_string = false, -+ // TextToTokenIds accepts UTF-8 text; llguidance must tokenize incomplete -+ // code points through the lossless vocabulary trie instead. -+ .tokenize_assumes_string = true, - .tokenize_fn = tokenize_fn, - .tokenize_user_data = &tokenizer, - }; ---- a/runtime/components/constrained_decoding/BUILD -+++ b/runtime/components/constrained_decoding/BUILD -@@ -336,6 +336,7 @@ - "//conditions:default": [], - }), - deps = [ -+ "@nlohmann_json//:json", - ":constraint", - ":constraint_provider", - ":constraint_provider_config", diff --git a/native/bridge/litert_cpu_options_identifier.patch b/native/bridge/litert_cpu_options_identifier.patch deleted file mode 100644 index 64b77f1..0000000 --- a/native/bridge/litert_cpu_options_identifier.patch +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/litert/c/options/litert_cpu_options.cc b/litert/c/options/litert_cpu_options.cc ---- a/litert/c/options/litert_cpu_options.cc -+++ b/litert/c/options/litert_cpu_options.cc -@@ -117,7 +117,9 @@ LiteRtStatus LrtGetOpaqueCpuOptionsData(const LrtCpuOptions* options, - return kLiteRtStatusOk; - } - --const char* LrtGetCpuOptionsIdentifier() { return "cpu_options"; } -+// Linux and Windows hosts run the upstream prebuilt libLiteRt, built before -+// LiteRT 724a247cc5 renamed this identifier; it reads only "xnnpack". -+const char* LrtGetCpuOptionsIdentifier() { return "xnnpack"; } - - LiteRtStatus LrtSetCpuOptionsKernelMode(LrtCpuOptions* options, - LiteRtCpuKernelMode mode) { diff --git a/native/bridge/litert_gpu_environment_destroy_callback.patch b/native/bridge/litert_gpu_environment_destroy_callback.patch deleted file mode 100644 index 3c840c3..0000000 --- a/native/bridge/litert_gpu_environment_destroy_callback.patch +++ /dev/null @@ -1,23 +0,0 @@ -diff --git a/litert/runtime/gpu_environment.cc b/litert/runtime/gpu_environment.cc ---- a/litert/runtime/gpu_environment.cc -+++ b/litert/runtime/gpu_environment.cc -@@ -200,6 +200,9 @@ - - Expected GpuEnvironment::Initialize( - const LiteRtEnvironmentOptionsT& environment_options) { -+ // Set up options. -+ options_ = CreateGpuEnvironmentOptions(environment_options); -+ - #if LITERT_HAS_OPENCL_SUPPORT - // Set up OpenCL. - LITERT_RETURN_IF_ERROR(tflite::gpu::cl::LoadOpenCL().ok()) -@@ -207,9 +210,6 @@ - properties_.is_opencl_available = true; - #endif // LITERT_HAS_OPENCL_SUPPORT - -- // Set up options. -- options_ = CreateGpuEnvironmentOptions(environment_options); -- - #if LITERT_HAS_OPENCL_SUPPORT - // Set up device. - if (options_.device_id && options_.platform_id) { diff --git a/native/bridge/litert_ios_framework_paths.patch b/native/bridge/litert_ios_framework_paths.patch deleted file mode 100644 index 19c9454..0000000 --- a/native/bridge/litert_ios_framework_paths.patch +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/litert/runtime/accelerators/gpu_registry.cc b/litert/runtime/accelerators/gpu_registry.cc -index 8b9bcb1..79233bd 100644 ---- a/litert/runtime/accelerators/gpu_registry.cc -+++ b/litert/runtime/accelerators/gpu_registry.cc -@@ -58,3 +58,4 @@ LiteRtStatus RegisterGpuAccelerator(LiteRtEnvironment environment) { - #elif TARGET_OS_IPHONE - #if LITERT_HAS_METAL_SUPPORT -- "libLiteRtMetalAccelerator" SO_EXT, -+ "@executable_path/Frameworks/LiteRtMetalAccelerator.framework/" -+ "LiteRtMetalAccelerator", diff --git a/native/bridge/litert_lm_bridge.c b/native/bridge/litert_lm_bridge.c index 66fa300..4fe9aa0 100644 --- a/native/bridge/litert_lm_bridge.c +++ b/native/bridge/litert_lm_bridge.c @@ -77,7 +77,7 @@ extern const char *litert_lm_stream_chunk_get_error( const LiteRtLmStreamChunk *chunk); #endif #if defined(LITERT_LM_FINISH_REASON_API) -// Defined in the runtime by stream_finish_reason.patch. +// Defined in the runtime by stream_finish_reason_v020.patch. extern int litert_lm_native_stream_chunk_get_finish_reason( const LiteRtLmStreamChunk *chunk); #endif diff --git a/native/bridge/litert_stage_spatial_tensors.patch b/native/bridge/litert_stage_spatial_tensors.patch deleted file mode 100644 index 7a73736..0000000 --- a/native/bridge/litert_stage_spatial_tensors.patch +++ /dev/null @@ -1,254 +0,0 @@ -diff --git a/ml_drift_delegate/delegate/gpu_backend_vulkan.cc b/ml_drift_delegate/delegate/gpu_backend_vulkan.cc -index 9cd89f1..d0062fe 100644 ---- a/ml_drift_delegate/delegate/gpu_backend_vulkan.cc -+++ b/ml_drift_delegate/delegate/gpu_backend_vulkan.cc -@@ -380,16 +380,42 @@ GpuInferenceContextVulkan::GpuInferenceContextVulkan( - num_nodes_per_command_buffer_(kDefaultMaxNumNodesPerCommandBuffer) {} - - GpuInferenceContextVulkan::~GpuInferenceContextVulkan() { -+ JoinNextCommandBuffersThread(); -+ if (post_dispatch_event_ != nullptr) { -+ post_dispatch_event_->Release(post_dispatch_event_); -+ } -+} -+ -+void GpuInferenceContextVulkan::JoinNextCommandBuffersThread() { - if (next_command_buffers_thread_) { - next_command_buffers_thread_->join(); -+ next_command_buffers_thread_.reset(); - } -- if (post_dispatch_event_ != nullptr) { -- post_dispatch_event_->Release(post_dispatch_event_); -+} -+ -+absl::Status GpuInferenceContextVulkan::FlushPendingSpatialTensors() { -+ if (pending_spatial_tensors_.empty()) { -+ return absl::OkStatus(); - } -+ auto pending = std::move(pending_spatial_tensors_); -+ pending_spatial_tensors_.clear(); -+ absl::MutexLock lock(ctx_mutex_); -+ for (const auto& [id, tensor] : pending) { -+ ABSL_RETURN_IF_ERROR(ctx_.SetTensor(id, tensor)); -+ } -+ return absl::OkStatus(); - } - - absl::StatusOr<::ml_drift::GpuSpatialTensor*> - GpuInferenceContextVulkan::GetSpatialTensor(::ml_drift::ValueId id) { -+ if (auto it = pending_spatial_tensors_.find(id); -+ it != pending_spatial_tensors_.end()) { -+ if (it->second == nullptr) { -+ return absl::NotFoundError( -+ absl::StrCat("No GPU tensor allocated for tensor id ", id, ".")); -+ } -+ return it->second; -+ } - absl::MutexLock lock(ctx_mutex_); - auto* tensor = ctx_.GetTensor(id); - if (tensor == nullptr) { -@@ -403,8 +429,13 @@ GpuInferenceContextVulkan::GetSpatialTensor(::ml_drift::ValueId id) { - - absl::Status GpuInferenceContextVulkan::BindSpatialTensor( - ::ml_drift::ValueId id, ::ml_drift::GpuSpatialTensor* tensor) { -+ auto* vk_tensor = static_cast(tensor); -+ if (!next_command_buffers_.empty()) { -+ pending_spatial_tensors_[id] = vk_tensor; -+ return absl::OkStatus(); -+ } - absl::MutexLock lock(ctx_mutex_); -- return ctx_.SetTensor(id, static_cast(tensor)); -+ return ctx_.SetTensor(id, vk_tensor); - } - - absl::Status GpuInferenceContextVulkan::WriteDataToWeightTensor( -@@ -436,9 +467,8 @@ absl::Status GpuInferenceContextVulkan::Dispatch() { - return shared_env.AddToPendingCommandBuffers(std::move(command_buffers)); - } - -- if (next_command_buffers_thread_) { -- next_command_buffers_thread_->join(); -- } -+ JoinNextCommandBuffersThread(); -+ ABSL_RETURN_IF_ERROR(FlushPendingSpatialTensors()); - - if (last_ctx_ != this) { - last_ctx_ = this; -@@ -557,6 +587,11 @@ absl::Status GpuInferenceContextVulkan::ReportMemoryBenchmarkIfEnabled( - - absl::Status GpuInferenceContextVulkan::SetCommandBufferHint( - int num_nodes_per_command_buffer) { -+ // Must be called before any Dispatch() call. -+ if (next_command_buffers_thread_ != nullptr) { -+ return absl::FailedPreconditionError( -+ "SetCommandBufferHint must be called before any Dispatch() call."); -+ } - num_nodes_per_command_buffer_ = num_nodes_per_command_buffer; - return absl::OkStatus(); - } -diff --git a/ml_drift_delegate/delegate/gpu_backend_vulkan.h b/ml_drift_delegate/delegate/gpu_backend_vulkan.h -index 9bfdc60..9c4b9f2 100644 ---- a/ml_drift_delegate/delegate/gpu_backend_vulkan.h -+++ b/ml_drift_delegate/delegate/gpu_backend_vulkan.h -@@ -228,6 +228,7 @@ class GpuInferenceContextVulkan : public GpuInferenceContext { - const override; - absl::Status ReportMemoryBenchmarkIfEnabled( - const ::ml_drift::CreateGpuModelInfo& create_info) override; -+ // Must be called before any Dispatch() call. - absl::Status SetCommandBufferHint(int num_nodes_per_command_buffer) override; - - // Underlying Vulkan inference context. -@@ -237,9 +238,17 @@ class GpuInferenceContextVulkan : public GpuInferenceContext { - } - - private: -+ void JoinNextCommandBuffersThread(); -+ absl::Status FlushPendingSpatialTensors(); -+ - GpuBackendVulkan* const backend_; - absl::Mutex ctx_mutex_; - ::ml_drift::syrtis::VulkanInferenceContext ctx_; -+ // Spatial tensor bindings staged while background command buffer preparation -+ // is enabled, applied to ctx_ once next_command_buffers_thread_ finishes. -+ absl::flat_hash_map<::ml_drift::ValueId, -+ ::ml_drift::syrtis::VulkanSpatialTensor*> -+ pending_spatial_tensors_; - - // Command buffers prepared ahead to reduce the overhead of command buffer - // preparation. -@@ -251,6 +260,9 @@ class GpuInferenceContextVulkan : public GpuInferenceContext { - // Whether next_command_buffers_ is ready to use. It's set to true when - // all next_command_buffers_ are prepared. - bool next_command_buffers_ready_ = false; -+ // Prepares next_command_buffers_ in parallel with the current Dispatch() -+ // call. JoinNextCommandBuffersThread() joins and resets it before flushing -+ // staged bindings to ctx_ or touching next_command_buffers_ again. - std::unique_ptr next_command_buffers_thread_; - - // Static member var indicating the last context which built the command -diff --git a/ml_drift_delegate/delegate/gpu_backend_webgpu.cc b/ml_drift_delegate/delegate/gpu_backend_webgpu.cc -index d0a6834..77ad89c 100644 ---- a/ml_drift_delegate/delegate/gpu_backend_webgpu.cc -+++ b/ml_drift_delegate/delegate/gpu_backend_webgpu.cc -@@ -418,13 +418,39 @@ GpuInferenceContextWebGpu::GpuInferenceContextWebGpu( - num_nodes_per_command_encoder_(kNumNodesPerCommandEncoder) {} - - GpuInferenceContextWebGpu::~GpuInferenceContextWebGpu() { -+ JoinNextCommandBuffersThread(); -+} -+ -+void GpuInferenceContextWebGpu::JoinNextCommandBuffersThread() { - if (next_command_buffers_thread_) { - next_command_buffers_thread_->join(); -+ next_command_buffers_thread_.reset(); -+ } -+} -+ -+absl::Status GpuInferenceContextWebGpu::FlushPendingSpatialTensors() { -+ if (pending_spatial_tensors_.empty()) { -+ return absl::OkStatus(); -+ } -+ auto pending = std::move(pending_spatial_tensors_); -+ pending_spatial_tensors_.clear(); -+ absl::MutexLock lock(backend_->memory_manager_mutex()); -+ for (const auto& [id, tensor] : pending) { -+ ABSL_RETURN_IF_ERROR(ctx_->SetTensor(id, tensor)); - } -+ return absl::OkStatus(); - } - - absl::StatusOr<::ml_drift::webgpu::SpatialTensor*> - GpuInferenceContextWebGpu::GetSpatialTensorInternal(::ml_drift::ValueId id) { -+ if (auto it = pending_spatial_tensors_.find(id); -+ it != pending_spatial_tensors_.end()) { -+ if (it->second == nullptr) { -+ return absl::NotFoundError( -+ absl::StrCat("No GPU tensor allocated for tensor id ", id, ".")); -+ } -+ return it->second; -+ } - absl::MutexLock lock(backend_->memory_manager_mutex()); - auto* tensor = ctx_->GetTensor(id); - if (tensor == nullptr) { -@@ -443,9 +469,13 @@ GpuInferenceContextWebGpu::GetSpatialTensor(::ml_drift::ValueId id) { - - absl::Status GpuInferenceContextWebGpu::BindSpatialTensor( - ::ml_drift::ValueId id, ::ml_drift::GpuSpatialTensor* tensor) { -+ auto* wgpu_tensor = static_cast<::ml_drift::webgpu::SpatialTensor*>(tensor); -+ if (!next_command_buffers_.empty()) { -+ pending_spatial_tensors_[id] = wgpu_tensor; -+ return absl::OkStatus(); -+ } - absl::MutexLock lock(backend_->memory_manager_mutex()); -- return ctx_->SetTensor( -- id, static_cast<::ml_drift::webgpu::SpatialTensor*>(tensor)); -+ return ctx_->SetTensor(id, wgpu_tensor); - } - - absl::Status GpuInferenceContextWebGpu::WriteDataToWeightTensor( -@@ -526,9 +556,8 @@ absl::Status GpuInferenceContextWebGpu::PrepareCommandBuffersFromCached( - /*submit_command_buffers=*/true); - } - -- if (next_command_buffers_thread_) { -- next_command_buffers_thread_->join(); -- } -+ JoinNextCommandBuffersThread(); -+ ABSL_RETURN_IF_ERROR(FlushPendingSpatialTensors()); - - if (last_ctx_ != this) { - last_ctx_ = this; -@@ -669,6 +698,11 @@ absl::Status GpuInferenceContextWebGpu::ReportMemoryBenchmarkIfEnabled( - - absl::Status GpuInferenceContextWebGpu::SetCommandBufferHint( - int num_nodes_per_command_encoder) { -+ // Must be called before any Dispatch() call. -+ if (next_command_buffers_thread_ != nullptr) { -+ return absl::FailedPreconditionError( -+ "SetCommandBufferHint must be called before any Dispatch() call."); -+ } - num_nodes_per_command_encoder_ = num_nodes_per_command_encoder; - return absl::OkStatus(); - } -diff --git a/ml_drift_delegate/delegate/gpu_backend_webgpu.h b/ml_drift_delegate/delegate/gpu_backend_webgpu.h -index 32d6b6f..dea1a01 100644 ---- a/ml_drift_delegate/delegate/gpu_backend_webgpu.h -+++ b/ml_drift_delegate/delegate/gpu_backend_webgpu.h -@@ -256,6 +256,7 @@ class GpuInferenceContextWebGpu : public GpuInferenceContext { - const override; - absl::Status ReportMemoryBenchmarkIfEnabled( - const ::ml_drift::CreateGpuModelInfo& create_info) override; -+ // Must be called before any Dispatch() call. - absl::Status SetCommandBufferHint(int num_nodes_per_command_encoder) override; - - // Underlying WebGPU inference context. -@@ -267,6 +268,8 @@ class GpuInferenceContextWebGpu : public GpuInferenceContext { - private: - absl::StatusOr<::ml_drift::webgpu::SpatialTensor*> GetSpatialTensorInternal( - ::ml_drift::ValueId id); -+ void JoinNextCommandBuffersThread(); -+ absl::Status FlushPendingSpatialTensors(); - // Prepares command buffers for Dispatch() call. - absl::Status PrepareCommandBuffers( - std::vector& command_buffers, -@@ -281,6 +284,10 @@ class GpuInferenceContextWebGpu : public GpuInferenceContext { - GpuBackendWebGpu* const backend_; - std::unique_ptr<::ml_drift::webgpu::InferenceContext> ctx_; - std::vector> async_upload_notifications_; -+ // Spatial tensor bindings staged while background command buffer preparation -+ // is enabled, applied to ctx_ once next_command_buffers_thread_ finishes. -+ absl::flat_hash_map<::ml_drift::ValueId, ::ml_drift::webgpu::SpatialTensor*> -+ pending_spatial_tensors_; - - // Command buffers prepared in advance for the next Dispatch() call. - std::vector> next_command_buffers_; -@@ -291,6 +298,9 @@ class GpuInferenceContextWebGpu : public GpuInferenceContext { - // Whether next_command_buffers_ is ready to use. It's set to true when - // all next_command_buffers_ are prepared. - bool next_command_buffers_ready_ = false; -+ // Prepares next_command_buffers_ in parallel with the current Dispatch() -+ // call. JoinNextCommandBuffersThread() joins and resets it before flushing -+ // staged bindings to ctx_ or touching next_command_buffers_ again. - std::unique_ptr next_command_buffers_thread_; - - // Static member var indicating the last context which built the command diff --git a/native/bridge/sentencepiece_bpe_null.patch b/native/bridge/sentencepiece_bpe_null.patch deleted file mode 100644 index bd61955..0000000 --- a/native/bridge/sentencepiece_bpe_null.patch +++ /dev/null @@ -1,57 +0,0 @@ -diff --git a/src/model_interface.h b/src/model_interface.h ---- a/src/model_interface.h -+++ b/src/model_interface.h -@@ -233,7 +233,8 @@ - // `reserved_id_map_` instead of `pieces_`. This excludes them from the main - // vocabulary map, which in turn prevents them from being merged during BPE - // segmentation (since BPE merge only looks up in `pieces_`). -- void InitializePieces(bool use_reserved_id_map); -+ void InitializePieces(bool use_reserved_id_map, -+ bool allow_bpe_null_piece = false); - - // Non-virtual (inlined) implementation for faster execution. - [[nodiscard]] float GetScoreInlined(int id) const { -diff --git a/src/model_interface.cc b/src/model_interface.cc ---- a/src/model_interface.cc -+++ b/src/model_interface.cc -@@ -64,7 +64,8 @@ - return unk_id_; - } - --void ModelInterface::InitializePieces(bool use_reserved_id_map) { -+void ModelInterface::InitializePieces(bool use_reserved_id_map, -+ bool allow_bpe_null_piece) { - pieces_.clear(); - reserved_id_map_.clear(); - unk_id_ = -1; -@@ -100,7 +101,16 @@ - status_ = absl::InternalError("piece must not be empty."); - return; - } -- if (sp.piece().find('\0') != absl::string_view::npos) { -+ // BPE NORMAL pieces use length-aware hash lookup, never the prefix trie. -+ // Preserve legacy single-NUL vocabulary IDs without admitting NUL trie keys. -+ const bool is_bpe_null_piece = -+ allow_bpe_null_piece && -+ model_proto_->trainer_spec().model_type() == TrainerSpec::BPE && -+ !model_proto_->trainer_spec().byte_fallback() && -+ sp.type() == ModelProto::SentencePiece::NORMAL && -+ sp.piece().size() == 1 && sp.piece()[0] == '\0'; -+ if (sp.piece().find('\0') != absl::string_view::npos && -+ !is_bpe_null_piece) { - status_ = absl::InternalError("piece must not include null character."); - return; - } -diff --git a/src/bpe_model.cc b/src/bpe_model.cc ---- a/src/bpe_model.cc -+++ b/src/bpe_model.cc -@@ -105,7 +105,8 @@ - // reserved_id_map_ (which BPE merge ignores). - // We use PieceToIdNoReserved() during inference to bypass reserved_id_map_ - // for performance. -- InitializePieces(/* use_reserved_id_map= */ false); -+ InitializePieces(/* use_reserved_id_map= */ false, -+ /* allow_bpe_null_piece= */ true); - } - - Model::~Model() {} diff --git a/native/bridge/step_zero_state_v0191.patch b/native/bridge/step_zero_state_v0191.patch deleted file mode 100644 index 1134952..0000000 --- a/native/bridge/step_zero_state_v0191.patch +++ /dev/null @@ -1,69 +0,0 @@ ---- a/runtime/executor/llm_litert_compiled_model_executor.cc -+++ b/runtime/executor/llm_litert_compiled_model_executor.cc -@@ -58,4 +58,5 @@ - #include "litert/cc/litert_tensor_buffer_types.h" // from @litert - #if defined(__APPLE__) -+#include - #include "litert/cc/options/litert_gpu_options.h" // from @litert - #endif // defined(__APPLE__) -@@ -1682,6 +1683,6 @@ - mtp_primed_ = false; - -- // We can keep our kv cache buffers if this is the first step. This lets us -- // restore from LlmContexts at step 0 with an empty kv cache. -+ // A context at step 0 has no state of its own: reset the state buffers -+ // instead of restoring them. - if (llm_context_->runtime_state().current_step > 0) { - auto restored_state = std::move( -@@ -1689,4 +1690,6 @@ - .state()); - ABSL_RETURN_IF_ERROR(RestoreState(std::move(restored_state))); -+ } else { -+ ABSL_RETURN_IF_ERROR(Reset()); - } - -@@ -1741,4 +1744,23 @@ - executor_settings_.GetAdvancedSettings()->sampler_handles_input; - } -+#if defined(__APPLE__) && TARGET_OS_OSX -+ if (sampler_handles_input && sampler_backend == Backend::GPU && -+ executor_settings_.GetBackend() == Backend::GPU && -+ executor_metadata_ != nullptr && -+ executor_metadata_->has_llm_executor_metadata() && -+ absl::c_any_of( -+ executor_metadata_->llm_executor_metadata().state_buffers(), -+ [](const proto::StateBuffer& state) { -+ return state.type() == proto::StateBuffer::TYPE_LINEAR_ATTENTION; -+ })) { -+ const auto options = env_.GetOptions(); -+ if (options.HasValue() && -+ options->GetOption(EnvironmentOptions::Tag::kWebGpuDevice).HasValue()) { -+ sampler_handles_input = false; -+ ABSL_LOG(INFO) << "Using executor-managed decode inputs for WebGPU " -+ "linear attention on macOS."; -+ } -+ } -+#endif - sampler_handles_input_ = - sampler_handles_input && sampler_->CanHandleInput() && -@@ -1892,4 +1914,7 @@ - return absl::OkStatus(); - } -+ if (new_step == 0) { -+ return Reset(); -+ } - RET_CHECK_LE(new_step, max_step).SetCode(absl::StatusCode::kInvalidArgument) - << "New step cannot be greater than the max step: " << max_step; -@@ -1908,4 +1933,12 @@ - llm_context_->runtime_state().current_step = 0; - mtp_primed_ = false; -+ // Linear attention summarizes all earlier tokens, including ones that a -+ // positional attention mask would hide in a KV cache. -+ if (state_ != nullptr) { -+ ABSL_RETURN_IF_ERROR(state_->Clear()); -+ } -+ if (decode_state_ != nullptr) { -+ ABSL_RETURN_IF_ERROR(decode_state_->Clear()); -+ } - return absl::OkStatus(); - } diff --git a/native/bridge/step_zero_state_v0191_test.patch b/native/bridge/step_zero_state_v0191_test.patch deleted file mode 100644 index 72b26d2..0000000 --- a/native/bridge/step_zero_state_v0191_test.patch +++ /dev/null @@ -1,400 +0,0 @@ -diff --git a/runtime/executor/BUILD b/runtime/executor/BUILD -index 8ef5be9..1211a84 100644 ---- a/runtime/executor/BUILD -+++ b/runtime/executor/BUILD -@@ -485,7 +485,10 @@ cc_test( - "//runtime/util:litert_status_util", - "//runtime/util:scoped_file", - "//runtime/util:test_utils", -- ], -+ ] + select({ -+ "@platforms//os:macos": ["//runtime/components:top_k_webgpu_sampler_static"], -+ "//conditions:default": [], -+ }), - ) - - cc_library( -diff --git a/runtime/executor/llm_litert_compiled_model_executor_test.cc b/runtime/executor/llm_litert_compiled_model_executor_test.cc -index d0cbd0f..8cc5ebf 100644 ---- a/runtime/executor/llm_litert_compiled_model_executor_test.cc -+++ b/runtime/executor/llm_litert_compiled_model_executor_test.cc -@@ -17,6 +17,10 @@ - #include - #include - #include -+#include -+#if defined(__APPLE__) -+#include -+#endif - #include // NOLINT: Required for path manipulation. - #include - #include -@@ -75,6 +79,9 @@ - namespace litert::lm { - namespace { - -+using ::testing::Contains; -+using ::testing::Each; -+using ::testing::Ne; - using ::testing::status::StatusIs; - - constexpr char kTestStaticModelPath[] = -@@ -645,6 +652,13 @@ class FakeSamplerWithInputHandling : public Sampler { - class TestableLlmLiteRtCompiledModelExecutorStatic - : public LlmLiteRtCompiledModelExecutorStatic { - public: -+ static void SetSamplerMetadataForTest( -+ LlmLiteRtCompiledModelExecutorStatic* executor, -+ const proto::ExecutorMetadata* metadata) { -+ executor->*&TestableLlmLiteRtCompiledModelExecutorStatic::executor_metadata_ = -+ metadata; -+ } -+ - static void SetSamplerForTest(LlmLiteRtCompiledModelExecutorStatic* executor, - std::unique_ptr sampler) { - auto* testable = -@@ -1118,6 +1132,10 @@ class TfLiteModelResources : public ModelResources { - with_mtp_drafter_ = with_mtp_drafter; - } - -+ void set_executor_metadata(proto::ExecutorMetadata executor_metadata) { -+ executor_metadata_ = std::move(executor_metadata); -+ } -+ - // ModelResources implementation: - absl::StatusOr GetTFLiteModel( - proto::LlmMetadata::TfLiteModelType model_type) override { -@@ -1150,6 +1168,9 @@ class TfLiteModelResources : public ModelResources { - - absl::StatusOr GetExecutorMetadata() - override { -+ if (executor_metadata_.has_value()) { -+ return &*executor_metadata_; -+ } - return absl::UnimplementedError("GetExecutorMetadata not implemented."); - } - -@@ -1181,6 +1202,7 @@ class TfLiteModelResources : public ModelResources { - private: - Model model_; - bool with_mtp_drafter_; -+ std::optional executor_metadata_; - }; - - TEST(LlmLiteRtCompiledModelExecutorStaticTest, -@@ -1775,6 +1797,315 @@ TEST(LlmLiteRtCompiledModelExecutorStaticTest, - EXPECT_EQ(step_and_token.token.size(), 1); - } - -+// Fills the tensor buffer `name` in `tensor_buffers` with `value`. -+void FillTensorBuffer( -+ absl::flat_hash_map& tensor_buffers, -+ absl::string_view name, uint8_t value) { -+ ASSERT_TRUE(tensor_buffers.contains(name)) << name; -+ TensorBuffer& buffer = tensor_buffers[name]; -+ LITERT_ASSERT_OK_AND_ASSIGN(size_t size, buffer.PackedSize()); -+ LITERT_ASSERT_OK_AND_ASSIGN( -+ auto lock_and_addr, -+ TensorBufferScopedLock::Create(buffer, TensorBuffer::LockMode::kWrite)); -+ std::memset(lock_and_addr.second, value, size); -+} -+ -+// Copies the contents of the tensor buffer `name` in `tensor_buffers` into -+// `contents`. -+void CopyTensorBufferContents( -+ absl::flat_hash_map& tensor_buffers, -+ absl::string_view name, std::vector& contents) { -+ ASSERT_TRUE(tensor_buffers.contains(name)) << name; -+ TensorBuffer& buffer = tensor_buffers[name]; -+ LITERT_ASSERT_OK_AND_ASSIGN(size_t size, buffer.PackedSize()); -+ LITERT_ASSERT_OK_AND_ASSIGN( -+ auto lock_and_addr, -+ TensorBufferScopedLock::Create(buffer, TensorBuffer::LockMode::kRead)); -+ const auto* data = static_cast(lock_and_addr.second); -+ contents.assign(data, data + size); -+} -+ -+// Tests that a new sequence (Reset(), a new context, or a rewind to step 0) -+// starts from zeroed state buffers, which a linear attention state needs. The -+// magic test models have one layer of KV cache: kv_cache_k_0 is -+// [1, batch, context_length, 64] and kv_cache_v_0 is -+// [1, batch, 64, context_length]. Most tests declare kv_cache_k_0 as a linear -+// attention state in the executor metadata. They check the contents of the -+// state buffers when the prefill graph runs. -+class LlmLiteRtCompiledModelExecutorLinearAttentionTest -+ : public ::testing::Test { -+ protected: -+ static constexpr absl::string_view kKeyCacheName = "kv_cache_k_0"; -+ static constexpr absl::string_view kValueCacheName = "kv_cache_v_0"; -+ -+ void CreateExecutor(absl::string_view model_file, -+ bool with_linear_attention_state, -+ Backend backend = Backend::CPU, -+ bool sampler_handles_input = true) { -+ const std::filesystem::path model_path = -+ std::filesystem::path(::testing::SrcDir()) / -+ absl::StrCat("litert_lm/runtime/testdata/", model_file); -+ ASSERT_OK_AND_ASSIGN(auto model_assets, -+ ModelAssets::Create(model_path.string())); -+ ASSERT_OK_AND_ASSIGN(auto executor_settings, -+ LlmExecutorSettings::CreateDefault(model_assets, backend)); -+ executor_settings.SetCacheDir(":nocache"); -+ executor_settings.SetAdvancedSettings( -+ AdvancedSettings{.sampler_handles_input = sampler_handles_input}); -+ LITERT_ASSERT_OK_AND_ASSIGN( -+ auto env, Environment::Create(std::vector())); -+ env_ = std::move(env); -+ ASSERT_OK_AND_ASSIGN(resources_, -+ TfLiteModelResources::Create(model_assets)); -+ if (with_linear_attention_state) { -+ proto::ExecutorMetadata executor_metadata; -+ AddStateBuffer(kKeyCacheName, proto::StateBuffer::TYPE_LINEAR_ATTENTION, -+ executor_metadata); -+ AddStateBuffer(kValueCacheName, -+ proto::StateBuffer::TYPE_GLOBAL_VALUE_CACHE, -+ executor_metadata) -+ ->set_sequence_axis(3); -+ resources_->set_executor_metadata(std::move(executor_metadata)); -+ } -+ ASSERT_OK_AND_ASSIGN(executor_, -+ LlmLiteRtCompiledModelExecutorStatic::Create( -+ std::move(executor_settings), *env_, *resources_)); -+ } -+ -+ // Prefills five tokens. -+ absl::Status Prefill() { -+ const std::vector input_tokens = {1, 2, 3, 4, 5}; -+ LITERT_ASSIGN_OR_RETURN( -+ auto input_tokens_buffer, -+ CopyToTensorBuffer(absl::MakeConstSpan(input_tokens), {1, 5})); -+ ExecutorInputs inputs; -+ inputs.SetTextData(ExecutorTextData(std::move(input_tokens_buffer))); -+ return executor_->Prefill(inputs); -+ } -+ -+ // Fills the state buffers with a non-zero value before each graph run, to -+ // stand in for the state left by the tokens processed before. -+ void FillStateBuffersBeforeEachGraphRun() { -+ executor_->UpdatePreGraphRunCallback( -+ [](absl::string_view /*signature_name*/, int /*current_step*/, -+ absl::flat_hash_map& -+ tensor_buffers) { -+ FillTensorBuffer(tensor_buffers, kKeyCacheName, 7); -+ FillTensorBuffer(tensor_buffers, kValueCacheName, 7); -+ }); -+ } -+ -+ // Copies the contents of the state buffers into `key_cache_` and -+ // `value_cache_` before each graph run. -+ void RecordStateBuffersBeforeEachGraphRun() { -+ executor_->UpdatePreGraphRunCallback( -+ [this](absl::string_view /*signature_name*/, int /*current_step*/, -+ absl::flat_hash_map& -+ tensor_buffers) { -+ CopyTensorBufferContents(tensor_buffers, kKeyCacheName, key_cache_); -+ CopyTensorBufferContents(tensor_buffers, kValueCacheName, -+ value_cache_); -+ }); -+ } -+ -+ std::optional env_; -+ std::unique_ptr resources_; -+ std::unique_ptr executor_; -+ std::vector key_cache_; -+ std::vector value_cache_; -+ -+ private: -+ // Adds the tensor `name` of the prefill and decode signatures as a state -+ // buffer of `type`. -+ static proto::StateBuffer* AddStateBuffer( -+ absl::string_view name, proto::StateBuffer::Type type, -+ proto::ExecutorMetadata& executor_metadata) { -+ proto::StateBuffer* state_buffer = -+ executor_metadata.mutable_llm_executor_metadata()->add_state_buffers(); -+ const std::string tensor_name(name); -+ state_buffer->set_prefill_input_name(tensor_name); -+ state_buffer->set_prefill_output_name(tensor_name); -+ state_buffer->set_decode_input_name(tensor_name); -+ state_buffer->set_decode_output_name(tensor_name); -+ state_buffer->set_type(type); -+ return state_buffer; -+ } -+}; -+ -+TEST_F(LlmLiteRtCompiledModelExecutorLinearAttentionTest, -+ PrefillAfterResetStartsFromZeroState) { -+ ASSERT_NO_FATAL_FAILURE(CreateExecutor("magic_test_none.tflite", -+ /*with_linear_attention_state=*/true)); -+ FillStateBuffersBeforeEachGraphRun(); -+ ASSERT_OK(Prefill()); -+ ASSERT_OK(executor_->Decode()); -+ -+ ASSERT_OK(executor_->Reset()); -+ RecordStateBuffersBeforeEachGraphRun(); -+ ASSERT_OK(Prefill()); -+ -+ EXPECT_THAT(key_cache_, Each(0)); -+ EXPECT_THAT(value_cache_, Each(0)); -+} -+ -+TEST_F(LlmLiteRtCompiledModelExecutorLinearAttentionTest, -+ PrefillInNewContextStartsFromZeroState) { -+ ASSERT_NO_FATAL_FAILURE(CreateExecutor("magic_test_none.tflite", -+ /*with_linear_attention_state=*/true)); -+ FillStateBuffersBeforeEachGraphRun(); -+ ASSERT_OK(Prefill()); -+ ASSERT_OK(executor_->Decode()); -+ -+ // A new conversation on a shared engine restores a new context at step 0. -+ ASSERT_OK_AND_ASSIGN( -+ auto context, -+ executor_->CreateNewContext(/*lora_id=*/std::nullopt, RuntimeConfig())); -+ ASSERT_OK(executor_->RestoreContext(std::move(context))); -+ RecordStateBuffersBeforeEachGraphRun(); -+ ASSERT_OK(Prefill()); -+ -+ EXPECT_THAT(key_cache_, Each(0)); -+ EXPECT_THAT(value_cache_, Each(0)); -+} -+ -+TEST_F(LlmLiteRtCompiledModelExecutorLinearAttentionTest, -+ RestoreContextAtStepZeroStartsFromZeroState) { -+ ASSERT_NO_FATAL_FAILURE(CreateExecutor("magic_test_none.tflite", -+ /*with_linear_attention_state=*/true)); -+ // A context saved before its first prefill is at step 0. -+ ASSERT_OK_AND_ASSIGN(auto context, executor_->CloneContext()); -+ ASSERT_EQ(context->runtime_state().current_step, 0); -+ FillStateBuffersBeforeEachGraphRun(); -+ ASSERT_OK(Prefill()); -+ ASSERT_OK(executor_->Decode()); -+ -+ // The state buffers belong to the executor and still hold the sequence that -+ // just ran; restoring the context at step 0 must not continue from it. -+ ASSERT_OK(executor_->RestoreContext(std::move(context))); -+ RecordStateBuffersBeforeEachGraphRun(); -+ ASSERT_OK(Prefill()); -+ -+ EXPECT_THAT(key_cache_, Each(0)); -+ EXPECT_THAT(value_cache_, Each(0)); -+} -+ -+TEST_F(LlmLiteRtCompiledModelExecutorLinearAttentionTest, -+ PrefillAfterRewindToStepZeroStartsFromZeroState) { -+ ASSERT_NO_FATAL_FAILURE(CreateExecutor("magic_test_none.tflite", -+ /*with_linear_attention_state=*/true)); -+ FillStateBuffersBeforeEachGraphRun(); -+ ASSERT_OK(Prefill()); -+ ASSERT_OK(executor_->Decode()); -+ -+ ASSERT_OK(executor_->SetCurrentStep(0)); -+ RecordStateBuffersBeforeEachGraphRun(); -+ ASSERT_OK(Prefill()); -+ -+ EXPECT_THAT(key_cache_, Each(0)); -+ EXPECT_THAT(value_cache_, Each(0)); -+} -+ -+TEST_F(LlmLiteRtCompiledModelExecutorLinearAttentionTest, -+ PrefillAtNonZeroStepKeepsLinearAttentionState) { -+ ASSERT_NO_FATAL_FAILURE(CreateExecutor("magic_test_none.tflite", -+ /*with_linear_attention_state=*/true)); -+ FillStateBuffersBeforeEachGraphRun(); -+ ASSERT_OK(Prefill()); -+ ASSERT_OK_AND_ASSIGN(int current_step, executor_->GetCurrentStep()); -+ ASSERT_EQ(current_step, 5); -+ -+ RecordStateBuffersBeforeEachGraphRun(); -+ ASSERT_OK(Prefill()); -+ -+ EXPECT_THAT(key_cache_, Contains(Ne(0))); -+} -+ -+TEST_F(LlmLiteRtCompiledModelExecutorLinearAttentionTest, -+ PrefillAfterResetStartsFromZeroKvCacheWithoutLinearAttentionState) { -+ ASSERT_NO_FATAL_FAILURE( -+ CreateExecutor("magic_test_none.tflite", -+ /*with_linear_attention_state=*/false)); -+ FillStateBuffersBeforeEachGraphRun(); -+ ASSERT_OK(Prefill()); -+ ASSERT_OK(executor_->Decode()); -+ -+ ASSERT_OK(executor_->Reset()); -+ RecordStateBuffersBeforeEachGraphRun(); -+ ASSERT_OK(Prefill()); -+ -+ EXPECT_THAT(key_cache_, Each(0)); -+ EXPECT_THAT(value_cache_, Each(0)); -+} -+ -+TEST_F(LlmLiteRtCompiledModelExecutorLinearAttentionTest, -+ PrefillAfterResetStartsFromZeroStateWithDecodeBatch) { -+ ASSERT_NO_FATAL_FAILURE(CreateExecutor("magic_test_decode_batch.tflite", -+ /*with_linear_attention_state=*/true)); -+ FillStateBuffersBeforeEachGraphRun(); -+ ASSERT_OK(Prefill()); -+ // Decode runs on the decode state, with one batch entry per output head. -+ ASSERT_OK_AND_ASSIGN(auto output_tokens, executor_->Decode()); -+ ASSERT_EQ(output_tokens.size(), kMaxDecodeBatchSize); -+ -+ ASSERT_OK(executor_->Reset()); -+ RecordStateBuffersBeforeEachGraphRun(); -+ // The prefill copies the state of the first output head back from the decode -+ // state, which Reset() zeroed too. -+ ASSERT_OK(Prefill()); -+ -+ EXPECT_THAT(key_cache_, Each(0)); -+ EXPECT_THAT(value_cache_, Each(0)); -+} -+ -+#if defined(__APPLE__) && TARGET_OS_OSX -+TEST_F(LlmLiteRtCompiledModelExecutorLinearAttentionTest, -+ SamplerLookaheadEligibilityOnMacOS) { -+ struct Case { -+ Backend backend; -+ bool linear_attention; -+ bool caller_enabled; -+ int first_decode_graphs; -+ }; -+ const Case cases[] = { -+ {Backend::GPU, true, true, 1}, -+ {Backend::GPU, false, true, 2}, -+ {Backend::CPU, true, true, 1}, -+ {Backend::GPU, true, false, 1}, -+ }; -+ for (const auto& test : cases) { -+ SCOPED_TRACE(absl::StrCat(static_cast(test.backend), "/", -+ test.linear_attention, "/", test.caller_enabled)); -+ proto::ExecutorMetadata metadata; -+ ASSERT_NO_FATAL_FAILURE(CreateExecutor("magic_test_none.tflite", false, -+ test.backend, test.caller_enabled)); -+ if (test.linear_attention) { -+ for (const char* name : {"kv_cache_lc_0", "kv_cache_lr_0"}) { -+ auto* state = metadata.mutable_llm_executor_metadata()->add_state_buffers(); -+ state->set_decode_input_name(name); -+ state->set_type(proto::StateBuffer::TYPE_LINEAR_ATTENTION); -+ } -+ // Provide the affected model's sampler metadata without changing the -+ // synthetic model's tensor names or its compiled state layout. -+ TestableLlmLiteRtCompiledModelExecutorStatic::SetSamplerMetadataForTest( -+ executor_.get(), &metadata); -+ } -+ int decode_graphs = 0; -+ executor_->UpdatePreGraphRunCallback( -+ [&decode_graphs](absl::string_view signature, int, auto&) { -+ if (signature == "decode") ++decode_graphs; -+ }); -+ ASSERT_OK(Prefill()); -+ ASSERT_OK(executor_->Decode()); -+ EXPECT_EQ(decode_graphs, test.first_decode_graphs); -+ ASSERT_OK(executor_->Decode()); -+ EXPECT_EQ(decode_graphs, test.first_decode_graphs + 1); -+ executor_.reset(); -+ resources_.reset(); -+ env_.reset(); -+ } -+} -+#endif -+ - absl::StatusOr< - std::pair, - std::unique_ptr>> diff --git a/native/bridge/stream_finish_reason.patch b/native/bridge/stream_finish_reason.patch deleted file mode 100644 index ebeb863..0000000 --- a/native/bridge/stream_finish_reason.patch +++ /dev/null @@ -1,307 +0,0 @@ ---- a/c/conversation.cc -+++ b/c/conversation.cc -@@ -40,15 +40,44 @@ - - namespace { - -+// litert-lm-native stream_proxy finish-reason wire values. -+enum FinishReason : int { -+ kFinishReasonUnknown = 0, -+ kFinishReasonStop = 1, -+ kFinishReasonLength = 2, -+ kFinishReasonContextExhausted = 3, -+ kFinishReasonCancelled = 4, -+ kFinishReasonError = 5, -+}; -+ -+int ToFinishReason(litert::lm::DecodeStopReason reason) { -+ switch (reason) { -+ case litert::lm::DecodeStopReason::kStopToken: -+ return kFinishReasonStop; -+ case litert::lm::DecodeStopReason::kMaxOutputTokens: -+ return kFinishReasonLength; -+ case litert::lm::DecodeStopReason::kMaxNumTokens: -+ return kFinishReasonContextExhausted; -+ case litert::lm::DecodeStopReason::kUnspecified: -+ return kFinishReasonUnknown; -+ } -+ return kFinishReasonUnknown; -+} -+ - absl::AnyInvocable)> --CreateConversationCallback(LiteRtLmStreamCallback callback, void* user_data) { -- return [callback, user_data](absl::StatusOr message) { -+CreateConversationCallback(LiteRtLmStreamCallback callback, void* user_data, -+ const litert::lm::Conversation* conversation) { -+ return [callback, user_data, -+ conversation](absl::StatusOr message) { - if (!message.ok()) { - std::string error_str = message.status().ToString(); - LiteRtLmStreamChunk chunk; - chunk.text = nullptr; - chunk.is_final = true; - chunk.error_msg = error_str.c_str(); -+ chunk.finish_reason = absl::IsCancelled(message.status()) -+ ? kFinishReasonCancelled -+ : kFinishReasonError; - callback(user_data, &chunk); - return; - } -@@ -57,6 +86,8 @@ CreateConversationCallback(LiteRtLmStreamCallback callback, void* user_data) { - chunk.text = nullptr; - chunk.is_final = true; - chunk.error_msg = nullptr; -+ chunk.finish_reason = -+ ToFinishReason(conversation->GetLastDecodeStopReason()); - callback(user_data, &chunk); - } else { - std::string json_str = message->dump(); -@@ -606,7 +637,9 @@ int litert_lm_conversation_send_message_stream( - conversation->conversation.get(), extra_context, optional_args); - - absl::Status status = conversation->conversation->SendMessageAsync( -- json_message, CreateConversationCallback(callback, callback_data), -+ json_message, -+ CreateConversationCallback(callback, callback_data, -+ conversation->conversation.get()), - std::move(litert_lm_optional_args)); - - if (!status.ok()) { -@@ -617,6 +650,12 @@ int litert_lm_conversation_send_message_stream( - return 0; - } - -+// Not part of the upstream C API: the litert-lm-native bridge reads it. -+int litert_lm_native_stream_chunk_get_finish_reason( -+ const LiteRtLmStreamChunk* chunk) { -+ return chunk == nullptr ? kFinishReasonUnknown : chunk->finish_reason; -+} -+ - const char* litert_lm_conversation_render_message_to_string( - LiteRtLmConversation* conversation, const char* message_json) { - if (!conversation || !conversation->conversation || !message_json) { ---- a/c/engine_internal.h -+++ b/c/engine_internal.h -@@ -47,6 +47,8 @@ struct LiteRtLmStreamChunk { - const char* text = nullptr; - bool is_final = false; - const char* error_msg = nullptr; -+ // litert-lm-native finish-reason wire value; 0 when not reported. -+ int finish_reason = 0; - }; - - struct LiteRtLmRepetitionPenaltyConfig { ---- a/runtime/conversation/conversation.cc -+++ b/runtime/conversation/conversation.cc -@@ -565,6 +565,7 @@ absl::Status Conversation::SendMessageAsync( - const Message& message, - absl::AnyInvocable)> user_callback, - OptionalArgs optional_args) { -+ last_decode_stop_reason_.store(DecodeStopReason::kUnspecified); - if (optional_args.args.has_value() && - engine_.GetEngineSettings().GetMaxVisionTokensPerImage().has_value()) { - ABSL_RETURN_IF_ERROR(ValidateVisualTokenBudget( -@@ -719,14 +720,30 @@ absl::Status Conversation::SendMessageAsync( - - auto internal_callback = - std::make_shared)>>( -- CreateInternalCallback( -- *model_data_processor_, -- optional_args.args.value_or(std::monostate()), -- config_.GetChannels(), std::move(user_callback), -- std::move(cancel_callback), std::move(complete_message_callback), -- open_channel_name, config_.return_error_on_max_tokens_reached(), -- config_.stream_tool_calls(), -- config_.stream_tool_calls_channel_name())); -+ [this, -+ callback = CreateInternalCallback( -+ *model_data_processor_, -+ optional_args.args.value_or(std::monostate()), -+ config_.GetChannels(), std::move(user_callback), -+ std::move(cancel_callback), -+ std::move(complete_message_callback), open_channel_name, -+ config_.return_error_on_max_tokens_reached(), -+ config_.stream_tool_calls(), -+ config_.stream_tool_calls_channel_name())]( -+ absl::StatusOr responses) mutable { -+ if (responses.ok() && -+ IsTaskEndState(responses->GetTaskState())) { -+ DecodeStopReason reason = responses->GetDecodeStopReason(); -+ // A prefill can fill the context before any decode step. -+ if (reason == DecodeStopReason::kUnspecified && -+ responses->GetTaskState() == -+ TaskState::kMaxNumTokensReached) { -+ reason = DecodeStopReason::kMaxNumTokens; -+ } -+ last_decode_stop_reason_.store(reason); -+ } -+ callback(std::move(responses)); -+ }); - - ABSL_ASSIGN_OR_RETURN( - auto decode_config, ---- a/runtime/conversation/conversation.h -+++ b/runtime/conversation/conversation.h -@@ -15,6 +15,7 @@ - #ifndef THIRD_PARTY_ODML_LITERT_LM_RUNTIME_CONVERSATION_CONVERSATION_H_ - #define THIRD_PARTY_ODML_LITERT_LM_RUNTIME_CONVERSATION_CONVERSATION_H_ - -+#include - #include - #include - #include -@@ -618,6 +619,12 @@ class Conversation { - // decode). - absl::StatusOr GetTokenCount() const; - -+ // Returns why the latest SendMessageAsync decode stopped. It is set before -+ // the final user callback and reset when the next message is sent. -+ DecodeStopReason GetLastDecodeStopReason() const { -+ return last_decode_stop_reason_.load(); -+ } -+ - // Returns the benchmark info for the conversation. Under the hood, this - // method triggers the benchmark info collection from the Session. Returns: - // - The benchmark info for the conversation. -@@ -791,6 +798,9 @@ class Conversation { - // Whether the current conversation is in message appending state. - bool is_appending_message_ ABSL_GUARDED_BY(history_mutex_) = false; - -+ std::atomic last_decode_stop_reason_{ -+ DecodeStopReason::kUnspecified}; -+ - // Mutex for task_controllers_. - mutable absl::Mutex task_controllers_mutex_; - // Map of task group id to task controllers. ---- a/runtime/core/tasks.cc -+++ b/runtime/core/tasks.cc -@@ -89,28 +89,30 @@ int TryGetMaxNumTokens(const LlmExecutor& executor) { - return settings->GetMaxNumTokens(); - } - --// Check whether the decoding loop should stop. --bool ShouldStop(bool hit_stop_tokens, int benchmark_decode_token_count, -- int num_decoded_steps, int current_step, int max_num_tokens, -- int max_output_tokens) { -+// Check whether the decoding loop should stop, and why. -+// Returns kUnspecified when decoding should continue. -+DecodeStopReason ShouldStop(bool hit_stop_tokens, -+ int benchmark_decode_token_count, -+ int num_decoded_steps, int current_step, -+ int max_num_tokens, int max_output_tokens) { - // Stopping conditions. - if (hit_stop_tokens && benchmark_decode_token_count == 0) { - // Only early stop if no decode step - // is requested by benchmark. -- return true; -+ return DecodeStopReason::kStopToken; - } else if (benchmark_decode_token_count > 0 && - num_decoded_steps >= benchmark_decode_token_count) { - // Stop when the number of decode steps is equal to the - // benchmark_decode_token_count (when specified). -- return true; -+ return DecodeStopReason::kMaxOutputTokens; - } else if (current_step >= max_num_tokens) { - // Reaching maximum number of kv-cache size. -- return true; -+ return DecodeStopReason::kMaxNumTokens; - } else if (num_decoded_steps >= max_output_tokens) { - // Reaching maximum number of output tokens. -- return true; -+ return DecodeStopReason::kMaxOutputTokens; - } -- return false; -+ return DecodeStopReason::kUnspecified; - } - - // A helper class to filter the token stream based on stop tokens. -@@ -662,6 +664,7 @@ absl::StatusOr Decode( - benchmark_info, sampler, std::move(repetition_penalty_config), - std::move(no_repeat_ngram_config), std::move(suppress_tokens_config), - constraint, cancelled, enable_speculative_decoding)); -+ DecodeStopReason stop_reason = DecodeStopReason::kUnspecified; - while (true) { - if (cancelled != nullptr && cancelled->load()) { - if (benchmark_info.has_value()) { -@@ -748,8 +751,10 @@ absl::StatusOr Decode( - - ABSL_ASSIGN_OR_RETURN(int current_step, executor.GetCurrentStep()); - int num_decode_steps = current_step - executor_step_before_decode; -- if (ShouldStop(*all_done, benchmark_decode_token_count, num_decode_steps, -- current_step, max_num_tokens, max_output_tokens)) { -+ stop_reason = -+ ShouldStop(*all_done, benchmark_decode_token_count, num_decode_steps, -+ current_step, max_num_tokens, max_output_tokens); -+ if (stop_reason != DecodeStopReason::kUnspecified) { - break; - } - } -@@ -827,10 +832,11 @@ absl::StatusOr Decode( - } - - if (is_streaming) { -- if (executor.GetCurrentStep().value() >= max_num_tokens) { -- return Responses(TaskState::kMaxNumTokensReached); -- } -- return Responses(TaskState::kDone); -+ Responses responses(executor.GetCurrentStep().value() >= max_num_tokens -+ ? TaskState::kMaxNumTokensReached -+ : TaskState::kDone); -+ responses.SetDecodeStopReason(stop_reason); -+ return responses; - } - - // Finalize scores for non-streaming custom sampling. -@@ -846,9 +852,11 @@ absl::StatusOr Decode( - TaskState task_state = executor.GetCurrentStep().value() >= max_num_tokens - ? TaskState::kMaxNumTokensReached - : TaskState::kDone; -- return Responses(std::move(task_state), std::move(final_texts), -- std::move(final_scores), /*token_lengths=*/{}, -- std::move(final_token_ids)); -+ Responses responses(std::move(task_state), std::move(final_texts), -+ std::move(final_scores), /*token_lengths=*/{}, -+ std::move(final_token_ids)); -+ responses.SetDecodeStopReason(stop_reason); -+ return responses; - } - - absl::StatusOr Score( ---- a/runtime/engine/io_types.h -+++ b/runtime/engine/io_types.h -@@ -89,6 +89,14 @@ enum class TaskState { - }; - std::ostream& operator<<(std::ostream& os, const TaskState& task_state); - -+// Why a decode loop stopped, in upstream ShouldStop precedence order. -+enum class DecodeStopReason { -+ kUnspecified, // Not a finished decode. -+ kStopToken, // A stop token or stop sequence was decoded. -+ kMaxOutputTokens, // The output-token budget was reached. -+ kMaxNumTokens, // The KV cache (context window) is full. -+}; -+ - bool IsTaskEndState(const TaskState& task_state); - - // A container to host the model responses. -@@ -114,6 +122,11 @@ class Responses { - // Sets the task state. - void SetTaskState(TaskState task_state) { task_state_ = task_state; } - -+ DecodeStopReason GetDecodeStopReason() const { return decode_stop_reason_; } -+ void SetDecodeStopReason(DecodeStopReason reason) { -+ decode_stop_reason_ = reason; -+ } -+ - // Returns the const texts vector. - // The returned vector contains the response texts for each candidate output - // string. In most cases, the candidate number is 1, the vector will contain a -@@ -166,6 +179,8 @@ class Responses { - // The state of the task. - TaskState task_state_; - -+ DecodeStopReason decode_stop_reason_ = DecodeStopReason::kUnspecified; -+ - // The output vector of response tokens (as strings). - std::vector response_texts_; - diff --git a/native/bridge/stream_finish_reason_v019.patch b/native/bridge/stream_finish_reason_v019.patch deleted file mode 100644 index b28a84d..0000000 --- a/native/bridge/stream_finish_reason_v019.patch +++ /dev/null @@ -1,304 +0,0 @@ ---- a/c/conversation.cc -+++ b/c/conversation.cc -@@ -44,15 +44,44 @@ - - namespace { - -+// litert-lm-native stream_proxy finish-reason wire values. -+enum FinishReason : int { -+ kFinishReasonUnknown = 0, -+ kFinishReasonStop = 1, -+ kFinishReasonLength = 2, -+ kFinishReasonContextExhausted = 3, -+ kFinishReasonCancelled = 4, -+ kFinishReasonError = 5, -+}; -+ -+int ToFinishReason(litert::lm::DecodeStopReason reason) { -+ switch (reason) { -+ case litert::lm::DecodeStopReason::kStopToken: -+ return kFinishReasonStop; -+ case litert::lm::DecodeStopReason::kMaxOutputTokens: -+ return kFinishReasonLength; -+ case litert::lm::DecodeStopReason::kMaxNumTokens: -+ return kFinishReasonContextExhausted; -+ case litert::lm::DecodeStopReason::kUnspecified: -+ return kFinishReasonUnknown; -+ } -+ return kFinishReasonUnknown; -+} -+ - absl::AnyInvocable)> --CreateConversationCallback(LiteRtLmStreamCallback callback, void* user_data) { -- return [callback, user_data](absl::StatusOr message) { -+CreateConversationCallback(LiteRtLmStreamCallback callback, void* user_data, -+ const litert::lm::Conversation* conversation) { -+ return [callback, user_data, -+ conversation](absl::StatusOr message) { - if (!message.ok()) { - std::string error_str = message.status().ToString(); - LiteRtLmStreamChunk chunk; - chunk.text = nullptr; - chunk.is_final = true; - chunk.error_msg = error_str.c_str(); -+ chunk.finish_reason = absl::IsCancelled(message.status()) -+ ? kFinishReasonCancelled -+ : kFinishReasonError; - callback(user_data, &chunk); - return; - } -@@ -61,6 +90,8 @@ CreateConversationCallback(LiteRtLmStreamCallback callback, void* user_data) { - chunk.text = nullptr; - chunk.is_final = true; - chunk.error_msg = nullptr; -+ chunk.finish_reason = -+ ToFinishReason(conversation->GetLastDecodeStopReason()); - callback(user_data, &chunk); - } else { - std::string json_str = message->dump(); -@@ -667,7 +698,9 @@ LiteRtLmStatusCode litert_lm_conversation_send_message_stream( - conversation->conversation.get(), extra_context, optional_args); - - absl::Status status = conversation->conversation->SendMessageAsync( -- json_message, CreateConversationCallback(callback, callback_data), -+ json_message, -+ CreateConversationCallback(callback, callback_data, -+ conversation->conversation.get()), - std::move(litert_lm_optional_args)); - - if (!status.ok()) { -@@ -677,6 +710,12 @@ LiteRtLmStatusCode litert_lm_conversation_send_message_stream( - return kLiteRtLmStatusOk; - } - -+// Not part of the upstream C API: the litert-lm-native bridge reads it. -+int litert_lm_native_stream_chunk_get_finish_reason( -+ const LiteRtLmStreamChunk* chunk) { -+ return chunk == nullptr ? kFinishReasonUnknown : chunk->finish_reason; -+} -+ - LiteRtLmStatusCode litert_lm_conversation_render_message_to_string( - LiteRtLmConversation* conversation, const char* message_json, - const char** out_text) { ---- a/c/engine_internal.h -+++ b/c/engine_internal.h -@@ -48,6 +48,8 @@ struct LiteRtLmStreamChunk { - const char* text = nullptr; - bool is_final = false; - const char* error_msg = nullptr; -+ // litert-lm-native finish-reason wire value; 0 when not reported. -+ int finish_reason = 0; - }; - - struct LiteRtLmRepetitionPenaltyConfig { ---- a/runtime/conversation/conversation.cc -+++ b/runtime/conversation/conversation.cc -@@ -589,6 +589,7 @@ absl::Status Conversation::SendMessageAsync( - const Message& message, - absl::AnyInvocable)> user_callback, - OptionalArgs optional_args) { -+ last_decode_stop_reason_.store(DecodeStopReason::kUnspecified); - if (!message.is_object()) { - return absl::InvalidArgumentError("Message must be a JSON object."); - } -@@ -812,13 +813,28 @@ absl::Status Conversation::SendMessageAsync( - - auto internal_callback = - std::make_shared)>>( -- CreateInternalCallback( -- *model_data_processor_, std::move(data_processor_args), -- config_.GetChannels(), std::move(wrapped_user_callback), -- remove_turn_from_history, std::move(complete_message_callback), -- open_channel_name, config_.return_error_on_max_tokens_reached(), -- config_.stream_tool_calls(), -- config_.stream_tool_calls_channel_name())); -+ [this, -+ callback = CreateInternalCallback( -+ *model_data_processor_, std::move(data_processor_args), -+ config_.GetChannels(), std::move(wrapped_user_callback), -+ remove_turn_from_history, std::move(complete_message_callback), -+ open_channel_name, config_.return_error_on_max_tokens_reached(), -+ config_.stream_tool_calls(), -+ config_.stream_tool_calls_channel_name())]( -+ absl::StatusOr responses) mutable { -+ if (responses.ok() && -+ IsTaskEndState(responses->GetTaskState())) { -+ DecodeStopReason reason = responses->GetDecodeStopReason(); -+ // A prefill can fill the context before any decode step. -+ if (reason == DecodeStopReason::kUnspecified && -+ responses->GetTaskState() == -+ TaskState::kMaxNumTokensReached) { -+ reason = DecodeStopReason::kMaxNumTokens; -+ } -+ last_decode_stop_reason_.store(reason); -+ } -+ callback(std::move(responses)); -+ }); - - if (session_inputs.empty()) { - auto decode_task_controller = session_->RunDecodeAsync( ---- a/runtime/conversation/conversation.h -+++ b/runtime/conversation/conversation.h -@@ -15,6 +15,7 @@ - #ifndef THIRD_PARTY_ODML_LITERT_LM_RUNTIME_CONVERSATION_CONVERSATION_H_ - #define THIRD_PARTY_ODML_LITERT_LM_RUNTIME_CONVERSATION_CONVERSATION_H_ - -+#include - #include - #include - #include -@@ -635,6 +636,12 @@ class Conversation { - // decode). - absl::StatusOr GetTokenCount() const; - -+ // Returns why the latest SendMessageAsync decode stopped. It is set before -+ // the final user callback and reset when the next message is sent. -+ DecodeStopReason GetLastDecodeStopReason() const { -+ return last_decode_stop_reason_.load(); -+ } -+ - // Returns the number of tokens the given message would consume if added - // to the conversation, including template tokens and media (vision/audio) - // soft tokens. This does not mutate the conversation or the KV cache. -@@ -829,6 +836,9 @@ class Conversation { - // Whether the current conversation is in message appending state. - bool is_appending_message_ ABSL_GUARDED_BY(history_mutex_) = false; - -+ std::atomic last_decode_stop_reason_{ -+ DecodeStopReason::kUnspecified}; -+ - // Mutex for task_controllers_. - mutable absl::Mutex task_controllers_mutex_; - // Map of task group id to task controllers. ---- a/runtime/core/tasks.cc -+++ b/runtime/core/tasks.cc -@@ -92,28 +92,30 @@ int TryGetMaxNumTokens(const LlmExecutor& executor) { - return settings->GetMaxNumTokens(); - } - --// Check whether the decoding loop should stop. --bool ShouldStop(bool hit_stop_tokens, int benchmark_decode_token_count, -- int num_decoded_steps, int current_step, int max_num_tokens, -- int max_output_tokens) { -+// Check whether the decoding loop should stop, and why. -+// Returns kUnspecified when decoding should continue. -+DecodeStopReason ShouldStop(bool hit_stop_tokens, -+ int benchmark_decode_token_count, -+ int num_decoded_steps, int current_step, -+ int max_num_tokens, int max_output_tokens) { - // Stopping conditions. - if (hit_stop_tokens && benchmark_decode_token_count == 0) { - // Only early stop if no decode step - // is requested by benchmark. -- return true; -+ return DecodeStopReason::kStopToken; - } else if (benchmark_decode_token_count > 0 && - num_decoded_steps >= benchmark_decode_token_count) { - // Stop when the number of decode steps is equal to the - // benchmark_decode_token_count (when specified). -- return true; -+ return DecodeStopReason::kMaxOutputTokens; - } else if (current_step >= max_num_tokens) { - // Reaching maximum number of kv-cache size. -- return true; -+ return DecodeStopReason::kMaxNumTokens; - } else if (num_decoded_steps >= max_output_tokens) { - // Reaching maximum number of output tokens. -- return true; -+ return DecodeStopReason::kMaxOutputTokens; - } -- return false; -+ return DecodeStopReason::kUnspecified; - } - - // A helper class to filter the token stream based on stop tokens. -@@ -739,6 +741,7 @@ absl::StatusOr Decode( - benchmark_info, sampler, std::move(repetition_penalty_config), - std::move(no_repeat_ngram_config), std::move(suppress_tokens_config), - constraint, cancelled, speculative_decoding_config)); -+ DecodeStopReason stop_reason = DecodeStopReason::kUnspecified; - while (true) { - if (cancelled != nullptr && cancelled->load()) { - if (benchmark_info.has_value()) { -@@ -811,8 +814,10 @@ absl::StatusOr Decode( - - ABSL_ASSIGN_OR_RETURN(int current_step, executor.GetCurrentStep()); - int num_decode_steps = current_step - executor_step_before_decode; -- if (ShouldStop(*all_done, benchmark_decode_token_count, num_decode_steps, -- current_step, max_num_tokens, max_output_tokens)) { -+ stop_reason = -+ ShouldStop(*all_done, benchmark_decode_token_count, num_decode_steps, -+ current_step, max_num_tokens, max_output_tokens); -+ if (stop_reason != DecodeStopReason::kUnspecified) { - break; - } - } -@@ -866,10 +871,11 @@ absl::StatusOr Decode( - } - - if (is_streaming) { -- if (executor.GetCurrentStep().value() >= max_num_tokens) { -- return Responses(TaskState::kMaxNumTokensReached); -- } -- return Responses(TaskState::kDone); -+ Responses responses(executor.GetCurrentStep().value() >= max_num_tokens -+ ? TaskState::kMaxNumTokensReached -+ : TaskState::kDone); -+ responses.SetDecodeStopReason(stop_reason); -+ return responses; - } - - // Finalize scores for non-streaming custom sampling. -@@ -885,9 +891,11 @@ absl::StatusOr Decode( - TaskState task_state = executor.GetCurrentStep().value() >= max_num_tokens - ? TaskState::kMaxNumTokensReached - : TaskState::kDone; -- return Responses(std::move(task_state), std::move(final_texts), -- std::move(final_scores), /*token_lengths=*/{}, -- std::move(final_token_ids)); -+ Responses responses(std::move(task_state), std::move(final_texts), -+ std::move(final_scores), /*token_lengths=*/{}, -+ std::move(final_token_ids)); -+ responses.SetDecodeStopReason(stop_reason); -+ return responses; - } - - absl::StatusOr Score( ---- a/runtime/engine/io_types.h -+++ b/runtime/engine/io_types.h -@@ -89,6 +89,14 @@ enum class TaskState { - }; - std::ostream& operator<<(std::ostream& os, const TaskState& task_state); - -+// Why a decode loop stopped, in upstream ShouldStop precedence order. -+enum class DecodeStopReason { -+ kUnspecified, // Not a finished decode. -+ kStopToken, // A stop token or stop sequence was decoded. -+ kMaxOutputTokens, // The output-token budget was reached. -+ kMaxNumTokens, // The KV cache (context window) is full. -+}; -+ - bool IsTaskEndState(const TaskState& task_state); - - // A container to host the model responses. -@@ -114,6 +122,11 @@ class Responses { - // Sets the task state. - void SetTaskState(TaskState task_state) { task_state_ = task_state; } - -+ DecodeStopReason GetDecodeStopReason() const { return decode_stop_reason_; } -+ void SetDecodeStopReason(DecodeStopReason reason) { -+ decode_stop_reason_ = reason; -+ } -+ - // Returns the const texts vector. - // The returned vector contains the response texts for each candidate output - // string. In most cases, the candidate number is 1, the vector will contain a -@@ -166,6 +179,8 @@ class Responses { - // The state of the task. - TaskState task_state_; - -+ DecodeStopReason decode_stop_reason_ = DecodeStopReason::kUnspecified; -+ - // The output vector of response tokens (as strings). - std::vector response_texts_; - diff --git a/native/bridge/v0181_workspace_build.patch b/native/bridge/v0181_workspace_build.patch deleted file mode 100644 index 2315978..0000000 --- a/native/bridge/v0181_workspace_build.patch +++ /dev/null @@ -1,107 +0,0 @@ ---- a/.bazelrc -+++ b/.bazelrc -@@ -294,6 +294,16 @@ build:windows --host_copt=/d2ReducedOptimizeHugeFunctions - build:windows --copt=-D_ENABLE_EXTENDED_ALIGNED_STORAGE - build:windows --host_copt=-D_ENABLE_EXTENDED_ALIGNED_STORAGE - -+# XNNPACK's AVX512-BF16 GEMM configuration unconditionally references assembly -+# microkernels (`..._asm_amd64_avx512bf16_broadcast`) that are not assembled -+# under MSVC, so enabling the feature here fails to link. XNNPACK enabled it by -+# default for the whole x86 family in -+# https://github.com/google/XNNPACK/commit/0363fd2f2b, and its `x86` config -+# setting matches plain `windows_x86_64` (MSVC) whereas the previous `x86_64` -+# setting only matched the clang-cl, clang and mingw variants. Opt back out to -+# keep the behavior this build had before that change. -+build:windows --define=xnn_enable_avx512bf16=false -+ - # Enable the runfiles symlink tree on Windows. This makes it possible to build - # the pip package on Windows without an intermediate data-file archive, as the - # build_pip_package script in its current form (as of Aug 2023) uses the ---- a/WORKSPACE -+++ b/WORKSPACE -@@ -2,19 +2,6 @@ - - workspace(name = "litert_lm") - --# UPDATED = 2026-09-25 --LITERT_REF = "26895c9fbcc25c43faa8c1a98cd1fd28951602c3" -- --LITERT_SHA256 = "698811a8ec56f6a9bd7705ffaa75ff792cae03a67d3a759dbc84f2023493ee6f" -- --# Keep TensorFlow at this commit for now. Newer commits load --# `compatibility_proxy_repo` from `@rules_cc//cc:extensions.bzl` in --# `tensorflow/workspace1.bzl`, which the rules_cc version resolved by this --# WORKSPACE does not provide, breaking the bazel build (as of 2026-09-15). --TENSORFLOW_REF = "d9a8da74b4c3de28a39ab34ad007838d6bc30c67" -- --TENSORFLOW_SHA256 = "cd46b37c0f722d5a48c0accc9618cc5684c553332b913091023703461f318d9b" -- - # UPDATED = 2026-10-09 - LITERT_REF = "ca21dc99de51c76bdcc572afeea1dd937d3c9e5c" - -@@ -26,6 +13,18 @@ TENSORFLOW_SHA256 = "c99256ecac35ee2d7795de8ee8976afbcc47308edf2c8a04a20a5bd8ffd - - load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") - -+# Declared before `rules_shell_dependencies()` and `apple_rules_dependencies()` -+# because those macros also declare `bazel_skylib`, and the first declaration of -+# a repository wins. The pinned TensorFlow expects 1.9.0: its `@rules_cc` uses -+# the `scope` attribute on `bool_flag`, which older bazel_skylib releases do not -+# define. Keep this in sync with the version in TensorFlow's -+# `tensorflow/workspace3.bzl`. -+http_archive( -+ name = "bazel_skylib", -+ sha256 = "3b5b49006181f5f8ff626ef8ddceaa95e9bb8ad294f7b5d7b11ea9f7ddaf8c59", -+ urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.9.0/bazel-skylib-1.9.0.tar.gz"], -+) -+ - http_archive( - name = "rules_shell", - sha256 = "bc61ef94facc78e20a645726f64756e5e285a045037c7a61f65af2941f4c25e1", -@@ -120,6 +119,16 @@ http_archive( - url = "https://github.com/bazel-contrib/rules_kotlin/releases/download/v2.4.10/rules_kotlin-v2.4.10.tar.gz", - ) - -+# Android rules (must be declared before kotlin_repositories and tf_workspace to override -+# older versions whose com_android_dex and apksig archives lacked sha256 and mirror URLs; -+# pinned to v0.7.2 because v0.7.3+ requires @protobuf_maven for @com_google_protobuf//java/util) -+http_archive( -+ name = "rules_android", -+ sha256 = "0da7198c7c8bac7e11e08dca3c434617b8593075858716595672e9aeefbef2a7", -+ strip_prefix = "rules_android-0.7.2", -+ url = "https://github.com/bazelbuild/rules_android/releases/download/v0.7.2/rules_android-v0.7.2.tar.gz", -+) -+ - # Go rules and Gazelle for rules_android (must be declared before tf_workspace to override ancient versions) - http_archive( - name = "io_bazel_rules_go", -@@ -139,10 +148,6 @@ http_archive( - ], - ) - --load("@io_bazel_rules_go//go:deps.bzl", "go_rules_dependencies") -- --go_rules_dependencies() -- - # TensorFlow - http_archive( - name = "org_tensorflow", -@@ -162,6 +167,18 @@ load("@org_tensorflow//tensorflow:workspace3.bzl", "tf_workspace3") - - tf_workspace3() - -+load("@bazel_features//:deps.bzl", "bazel_features_deps") -+ -+bazel_features_deps() -+ -+load("@rules_cc//cc:extensions.bzl", "compatibility_proxy_repo") -+ -+compatibility_proxy_repo() -+ -+load("@io_bazel_rules_go//go:deps.bzl", "go_rules_dependencies") -+ -+go_rules_dependencies() -+ - load( - "@rules_ml_toolchain//cc/deps:cc_toolchain_deps.bzl", - "cc_toolchain_deps", diff --git a/tools/android_gpu_safety_patch.py b/tools/android_gpu_safety_patch.py index bbe67db..29e9743 100644 --- a/tools/android_gpu_safety_patch.py +++ b/tools/android_gpu_safety_patch.py @@ -1,21 +1,11 @@ """Audited C API preflight patch for the exact Android Qwen3 safety policy.""" import hashlib -import re from pathlib import Path -from source_patch_utils import apply_source_patch +from source_patch_utils import active_source_carries, apply_source_patch -PATCH_PATH = "native/bridge/android_gpu_safety_v019.patch" -# v0.19.1 leaves c/engine.cc and c/BUILD byte-identical to v0.19.0. -AUDITED_TAGS = frozenset({"v0.19.0", "v0.19.1", "v0.20.0"}) -SOURCES = {'c/engine.cc': ('d2cefd0a04312b5808daddf730a924e8b83e2b1cc6214a5a12e8b454d56557c2', - '9ad52a303234df359a5a47256c512823b691c6c0c656b9a388bd544edda320e7'), - 'c/BUILD': ('f72d6fc3e341497cc9cc5b8ba405b81d8aff1e9eed080cc5e4f281832e066748', - '6a653c953a0389e44c5cddce60911ee9e148ade08b1b5a087b7657adeeb54d7d')} - - -V020_PATCH_PATH = "native/bridge/android_gpu_safety_v020.patch" -V020_SOURCES = { +PATCH_PATH = "native/bridge/android_gpu_safety_v020.patch" +SOURCES = { "c/BUILD": ( "cdd78f10cbc226bd45602f868dc07ae44bb9ed9ca1c9bf1c965fa9d47c6b34fe", "78699dba1264eb02210c370d5741bcc8ab949cc368e3a3176be32a8feba41efb", @@ -27,46 +17,29 @@ } -def sources_for(tag: str) -> dict[str, tuple[str, str]]: - return V020_SOURCES if tag == "v0.20.0" else SOURCES - - -def patch_path_for(tag: str) -> str: - return V020_PATCH_PATH if tag == "v0.20.0" else PATCH_PATH - - -def applies(tag: str) -> bool: - if tag in AUDITED_TAGS: - return True - match = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", tag) - if match and tuple(map(int, match.groups())) < (0, 19, 0): - return False - raise RuntimeError("Android Qwen3 GPU safety has no audited decision for " + tag) - - def digest(path: Path) -> str: return hashlib.sha256(path.read_bytes().replace(b"\r\n", b"\n")).hexdigest() def apply(source_root: Path, tag: str) -> None: - if not applies(tag): + if not active_source_carries(tag): return - observed = {name: digest(source_root / name) for name in sources_for(tag)} - if all(observed[name] == post for name, (_, post) in sources_for(tag).items()): + observed = {name: digest(source_root / name) for name in SOURCES} + if all(observed[name] == post for name, (_, post) in SOURCES.items()): return - if any(observed[name] != pre for name, (pre, _) in sources_for(tag).items()): + if any(observed[name] != pre for name, (pre, _) in SOURCES.items()): raise RuntimeError("C API safety source changed; requalify Android GPU preflight") - patch = Path(__file__).resolve().parents[1] / patch_path_for(tag) + patch = Path(__file__).resolve().parents[1] / PATCH_PATH apply_source_patch(source_root, patch) - if any(digest(source_root / name) != post for name, (_, post) in sources_for(tag).items()): + if any(digest(source_root / name) != post for name, (_, post) in SOURCES.items()): raise RuntimeError("Android GPU preflight postimage mismatch") def manifest(tag: str) -> list[dict]: - if not applies(tag): + if not active_source_carries(tag): return [] - sha = hashlib.sha256((Path(__file__).resolve().parents[1] / patch_path_for(tag)).read_bytes()).hexdigest() - return [{"id": "android-qwen3-gpu-safety", "path": patch_path_for(tag), "sha256": sha, + sha = hashlib.sha256((Path(__file__).resolve().parents[1] / PATCH_PATH).read_bytes()).hexdigest() + return [{"id": "android-qwen3-gpu-safety", "path": PATCH_PATH, "sha256": sha, "source": name, "preimageSha256Lf": pre, "postimageSha256Lf": post, "scope": "source-built runtimes only; Android C API guard; excludes official upstream prebuilts"} - for name, (pre, post) in sources_for(tag).items()] + for name, (pre, post) in SOURCES.items()] diff --git a/tools/asr_litertlm_container_patch.py b/tools/asr_litertlm_container_patch.py deleted file mode 100644 index 4da9bf1..0000000 --- a/tools/asr_litertlm_container_patch.py +++ /dev/null @@ -1,62 +0,0 @@ -"""Identity of the carried v0.18 ASR `.litertlm` container routing backport.""" -import hashlib -import re -from pathlib import Path - -AUDITED_CONTAINER_TAGS = frozenset({"v0.18.0", "v0.18.1"}) -# v0.19.0 contains UPSTREAM_FIX_COMMIT and replaces AsrEngine with Omni session -# factories, which load the ASR section and tokenizer from the container; -# v0.19.1 keeps that source. -UPSTREAM_FIX_TAGS = frozenset({"v0.19.0", "v0.19.1", "v0.20.0"}) -PATCH_PATH = "native/bridge/asr_litertlm_container.patch" -# Upstream google-ai-edge/LiteRT-LM bfdec21732 ("Support ASR models in -# .litertlm") landed on main after the v0.18 release branch was cut. -UPSTREAM_FIX_COMMIT = "bfdec21732" -# LF-normalized (preimage, postimage) SHA-256 per patched v0.18.0 source. -SOURCES = { - "omni/asr/BUILD": ( - "495b4b4821fc768ca2733bdb18a45a0f6aac300771f9b1f1fa7bf76c98ee9b97", - "b19ed72004ed674549f48938613e1d03a8c1af322e9214aab7b37a37ab294c7e", - ), - "omni/asr/asr_engine.cc": ( - "96132de1f1d665d70585a2ef5ff64f5b432992c116f8f31b5f084679cc1f47d4", - "b92d66fda41b5a995d8a8a1a83b86067b003392d4be53d6821928064e0fe1fd4", - ), - "omni/asr/asr_engine.h": ( - "ace689b9bf490bee06e740d5965a99ee402bb194ed4ee29d425f2e651e365cf3", - "cdb5f862e6e0d46041de0c0a1f0bbff20e640258fab30a3d02ed519f3781dd4c", - ), -} - - -def require_container_patch_decision(compatibility_tag: str) -> bool: - """Returns whether the backport applies; newer sources need a decision.""" - version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", compatibility_tag) - if version and tuple(map(int, version.groups())) < (0, 18, 0): - return False - if compatibility_tag in UPSTREAM_FIX_TAGS: - return False - if compatibility_tag in AUDITED_CONTAINER_TAGS: - return True - raise RuntimeError( - f"ASR .litertlm container routing has no explicit decision for " - f"{compatibility_tag}; check for upstream {UPSTREAM_FIX_COMMIT}, then " - "revalidate the carried patch or record its retirement in " - "tools/asr_litertlm_container_patch.py and docs/upstream_patch_audit.md") - - -def container_patch_manifest(compatibility_tag: str) -> list[dict]: - if not require_container_patch_decision(compatibility_tag): - return [] - patch_sha256 = hashlib.sha256( - (Path(__file__).resolve().parents[1] / PATCH_PATH).read_bytes() - ).hexdigest() - return [{ - "id": "asr-litertlm-container", - "path": PATCH_PATH, - "sha256": patch_sha256, - "source": source, - "preimageSha256Lf": preimage, - "postimageSha256Lf": postimage, - "scope": "source-built runtimes only; excludes official upstream prebuilts", - } for source, (preimage, postimage) in SOURCES.items()] diff --git a/tools/asr_overlap_patch.py b/tools/asr_overlap_patch.py index 5b3c5f9..8c18a4d 100644 --- a/tools/asr_overlap_patch.py +++ b/tools/asr_overlap_patch.py @@ -1,52 +1,20 @@ -"""Identity of the carried v0.18 untimed merger source transformation.""" +"""Identity of the carried untimed merger patch and release patch inventory.""" import hashlib -import re from pathlib import Path from android_gpu_safety_patch import manifest as android_gpu_safety_manifest -from asr_litertlm_container_patch import container_patch_manifest from huggingface_token_bytes_patch import token_bytes_patch_manifest -from litert_cpu_options_identifier_patch import cpu_options_identifier_patch_manifest from litert_stage_spatial_tensors_patch import stage_spatial_tensors_patch_manifest -from step_zero_state_patch import manifest as step_zero_state_manifest +from source_patch_utils import active_source_carries from stream_finish_reason_patch import finish_reason_patch_manifest from windows_engine_fd_patch import manifest as windows_engine_fd_manifest -from workspace_build_patch import workspace_build_patch_manifest from xnnpack_pf32_sme2_patch import xnnpack_pf32_patch_manifest from xnnpack_pqs8_qc4w_sme2_patch import xnnpack_qc4w_patch_manifest -PREIMAGE_SHA256 = "6458bdfb32cbb32250c5be8843d303a9759da96f5675eae2d23a5f01f41dc826" -AUDITED_OVERLAP_TAGS = frozenset({"v0.18.0", "v0.18.1"}) -POSTIMAGE_SHA256 = "c320a49202fcaed40ef2619e977b3a44303e7aa9aa04012c94a6ca07c016caee" -PATCH_PATH = "native/bridge/asr_untimed_overlap.patch" -MERGER_SOURCE = "omni/asr/timestamp_text_merger.cc" -# v0.19.0 moved and rewrote the merger; its seam-run fallback still mis-seams -# repeated phrases at the bridge's 0.4 overlap (docs/asr_untimed_overlap.md). -# The v0.19.1 merger is byte-identical to v0.19.0. -V019_PREIMAGE_SHA256 = "1ddbc15f935d63ca123011e7e4864b33b78b8cd5ee292b9d3bccf90d2bdb378f" -V019_POSTIMAGE_SHA256 = "3b135f027b369ceadb734117d416071e4e64837304f49b90e77e8f9d19fec060" -V019_PATCH_PATH = "native/bridge/asr_untimed_overlap_v019.patch" -V019_MERGER_SOURCE = "omni/speech2text/timestamp_text_merger.cc" -V019_OVERLAP_TAGS = frozenset({"v0.19.0", "v0.19.1"}) - -V020_OVERLAP_TAG = "v0.20.0" -V020_PREIMAGE_SHA256 = "f6091439b29114fdb6cb010480e9b9b3961cd7c868925dc08f458f822ddecd65" -V020_POSTIMAGE_SHA256 = "4a7949344fb79d7c7e7c6fc4261b74031b1244f6bb83f741229483775efdd835" -OVERLAP_TAGS = AUDITED_OVERLAP_TAGS | V019_OVERLAP_TAGS | {V020_OVERLAP_TAG} - - -def merger_source(compatibility_tag: str) -> str: - return (V019_MERGER_SOURCE if compatibility_tag in V019_OVERLAP_TAGS | {V020_OVERLAP_TAG} - else MERGER_SOURCE) - - -def overlap_identity(compatibility_tag: str) -> tuple[str, str, str]: - """Returns the patch path, preimage and postimage for an audited tag.""" - if compatibility_tag == V020_OVERLAP_TAG: - return V019_PATCH_PATH, V020_PREIMAGE_SHA256, V020_POSTIMAGE_SHA256 - if compatibility_tag in V019_OVERLAP_TAGS: - return V019_PATCH_PATH, V019_PREIMAGE_SHA256, V019_POSTIMAGE_SHA256 - return PATCH_PATH, PREIMAGE_SHA256, POSTIMAGE_SHA256 +PATCH_PATH = "native/bridge/asr_untimed_overlap_v019.patch" +MERGER_SOURCE = "omni/speech2text/timestamp_text_merger.cc" +PREIMAGE_SHA256 = "f6091439b29114fdb6cb010480e9b9b3961cd7c868925dc08f458f822ddecd65" +POSTIMAGE_SHA256 = "4a7949344fb79d7c7e7c6fc4261b74031b1244f6bb83f741229483775efdd835" def source_sha256(data: bytes) -> str: @@ -54,45 +22,23 @@ def source_sha256(data: bytes) -> str: return hashlib.sha256(data.replace(b"\r\n", b"\n")).hexdigest() -def require_asr_patch_decision(compatibility_tag: str) -> None: - """Older releases predate this carry; newer/unknown sources need a decision. - - Deliberately no environment/CLI bypass: extending support means checking in - a revalidated patch or a documented, version-specific retirement decision. - """ - version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", compatibility_tag) - if version and tuple(map(int, version.groups())) < (0, 18, 0): - return - if compatibility_tag in OVERLAP_TAGS: - return - raise RuntimeError( - f"ASR untimed overlap has no explicit decision for {compatibility_tag}; " - "revalidate the carried patch or record a version-specific opt-out with " - "evidence in tools/asr_overlap_patch.py and docs/asr_untimed_overlap.md " - "before building or releasing this version") - - def source_patch_manifest(compatibility_tag: str) -> list[dict]: - require_asr_patch_decision(compatibility_tag) - carried = compatibility_tag in OVERLAP_TAGS - patch_path, preimage, postimage = overlap_identity(compatibility_tag) - overlap = [] if not carried else [{ + if not active_source_carries(compatibility_tag): + return [] + overlap = [{ "id": "asr-untimed-overlap", - "path": patch_path, - "sha256": hashlib.sha256((Path(__file__).resolve().parents[1] / patch_path).read_bytes()).hexdigest(), - "source": merger_source(compatibility_tag), - "preimageSha256Lf": preimage, - "postimageSha256Lf": postimage, + "path": PATCH_PATH, + "sha256": hashlib.sha256((Path(__file__).resolve().parents[1] / PATCH_PATH).read_bytes()).hexdigest(), + "source": MERGER_SOURCE, + "preimageSha256Lf": PREIMAGE_SHA256, + "postimageSha256Lf": POSTIMAGE_SHA256, "scope": "source-built runtimes only; excludes official upstream prebuilts", }] - return [*overlap, *container_patch_manifest(compatibility_tag), + return [*overlap, *finish_reason_patch_manifest(compatibility_tag), *android_gpu_safety_manifest(compatibility_tag), *windows_engine_fd_manifest(compatibility_tag), - *workspace_build_patch_manifest(compatibility_tag), *xnnpack_pf32_patch_manifest(compatibility_tag), *xnnpack_qc4w_patch_manifest(compatibility_tag), - *cpu_options_identifier_patch_manifest(compatibility_tag), *token_bytes_patch_manifest(compatibility_tag), - *step_zero_state_manifest(compatibility_tag), *stage_spatial_tensors_patch_manifest(compatibility_tag)] diff --git a/tools/build_upstream_runtime.py b/tools/build_upstream_runtime.py index a442470..81832b5 100644 --- a/tools/build_upstream_runtime.py +++ b/tools/build_upstream_runtime.py @@ -13,36 +13,30 @@ from android_protobuf_policy import validate_android_protobuf_isolation from android_gpu_safety_patch import apply as apply_android_gpu_safety -from asr_litertlm_container_patch import SOURCES as CONTAINER_PATCH_SOURCES, require_container_patch_decision -from asr_overlap_patch import OVERLAP_TAGS, merger_source, overlap_identity, source_sha256, require_asr_patch_decision +from asr_overlap_patch import ( + MERGER_SOURCE, + PATCH_PATH as ASR_PATCH_PATH, + POSTIMAGE_SHA256 as ASR_POSTIMAGE, + PREIMAGE_SHA256 as ASR_PREIMAGE, + source_sha256, +) from bazel_repository_provenance import release_workspace_rc, verify_resolved_archives from ios_runtime_policy import FST_DEFINE, provider_free_ios, validate_ios_directory, verify_upstream_fst_gate from download_utils import download_to_path from git_lfs_utils import materialize_git_lfs_libraries from gpu_environment_teardown import find_ndk_llvm_objdump, validate_library from huggingface_token_bytes_patch import apply as patch_huggingface_token_bytes -from litert_cpu_options_identifier_patch import ( - LITERT_ARCHIVE_SHA256 as CPU_OPTIONS_LITERT_ARCHIVE_SHA256, - LITERT_REF as CPU_OPTIONS_LITERT_REF, - SOURCES as CPU_OPTIONS_IDENTIFIER_SOURCES, - require_cpu_options_identifier_patch_decision, - verify_dynamic_runtime, -) from litert_lm_symbols import ( android_static_gpu_sampler_symbols, - has_asr_bridge, - has_omni_asr_engine, - has_prebuilt_topk_samplers, in_process_litert_abi_version, - is_at_least, - uses_c_api_v1, required_bridge_symbols, required_c_api_symbols, - uses_stream_chunk_api, ) from litert_stage_spatial_tensors_patch import ( - identity_for as stage_spatial_tensors_identity, - require_stage_spatial_tensors_patch_decision, + LITERT_REF as STAGING_LITERT_REF, + LITERT_ARCHIVE_SHA256 as STAGING_LITERT_SHA256, + PATCH_PATH as STAGING_PATCH_PATH, + SOURCES as STAGING_SOURCES, ) from macos_runtime_identity import normalize_macos_runtime_identity from macos_runtime_policy import UNSUPPORTED_MACOS_ARCH_REASON @@ -54,35 +48,24 @@ is_elf, is_system_needed, ) -from source_patch_utils import apply_source_patch -from step_zero_state_patch import apply as patch_step_zero_state +from source_patch_utils import active_source_carries, apply_source_patch from stream_finish_reason_patch import ( BAZEL_DEFINE as FINISH_REASON_DEFINE, - patch_path_for as finish_reason_patch_path, - require_finish_reason_patch_decision, - sources_for as finish_reason_patch_sources, + PATCH_PATH as FINISH_REASON_PATCH_PATH, + SOURCES as FINISH_REASON_SOURCES, ) from windows_dxc import stage_windows_dxc -from windows_engine_fd_patch import ( - apply as patch_windows_engine_fd, - require_windows_engine_fd_patch_decision, -) +from windows_engine_fd_patch import apply as patch_windows_engine_fd import windows_runtime -from workspace_build_patch import ( - PATCH_PATH as WORKSPACE_BUILD_PATCH_PATH, - SOURCES as WORKSPACE_BUILD_PATCH_SOURCES, - require_workspace_build_patch_decision, -) from xnnpack_pf32_sme2_patch import ( - V020_TENSORFLOW_REF, - archive_sha256_for as xnnpack_archive_sha256, - commit_for as xnnpack_commit, + TENSORFLOW_REF, + XNNPACK_SHA256, + XNNPACK_COMMIT, declare_patched_xnnpack, - require_xnnpack_pf32_patch_decision, - sources_for as xnnpack_pf32_sources, + SOURCES as XNNPACK_PF32_SOURCES, verify_patched_xnnpack_archive, ) -from xnnpack_pqs8_qc4w_sme2_patch import sources_for as xnnpack_qc4w_sources +from xnnpack_pqs8_qc4w_sme2_patch import SOURCES as XNNPACK_QC4W_SOURCES from upstream_archive import github_source_archive_url REPO_ROOT = Path(__file__).resolve().parents[1] @@ -97,22 +80,6 @@ "zlib-1.3.1.tar.gz" ) -# LiteRT commits known to need litert_gpu_environment_destroy_callback.patch: -# GpuEnvironment::Initialize returns on an OpenCL load failure before it -# records the environment options, so the WebGPU destroy callback is lost. -# LiteRT 9c8ae4e0fc records the options first. All four pin the same -# gpu_environment.cc. This is the set the patch has been matched against, not -# every affected commit: validate_android_gpu_environment_teardown fails an -# Android build of any other pin that still has the old ordering. -LITERT_REFS_WITHOUT_GPU_TEARDOWN_ORDERING = frozenset( - { - "3cb830ad9c94f9922f0a88dd431b005413628919", # LiteRT-LM v0.15.0 - "0ff28117f1cb5556d0e015bf80b773f74e2bee51", # LiteRT-LM v0.16.0, v0.16.1 - "761d99cb90e20c67efcb3fe1119a60c92381bd1a", # upstream development commits - "9fe5be45564c868408e6514c8aabb83e211a0911", # LiteRT-LM v0.17.0, v0.17.1 - } -) - RUNTIME_TARGETS = { ("android", "arm64"): { "bazel_target": "//bridge:libLiteRtLm.so", @@ -187,70 +154,33 @@ LIB_SUFFIXES = (".so", ".dylib", ".dll", ".lib", ".a") -def uses_shared_desktop_litert(platform: str, upstream_tag: str) -> bool: - """Whether a desktop host links upstream's prebuilt libLiteRt (v0.16-v0.18). - - LiteRT-LM hands external weights over by writing C++ members of LiteRT's - opaque options struct, which is ABI-valid only when LiteRT is compiled into - the host with the same C++ runtime, as on Apple and Android (#111). - """ - return (platform in {"linux", "windows"} - and is_at_least(upstream_tag, (0, 16, 0)) - and not is_at_least(upstream_tag, (0, 19, 0))) - - def patch_asr_untimed_overlap(source_root: Path, upstream_tag: str) -> None: """Carry #673 only on an audited source; require review on drift.""" - require_asr_patch_decision(upstream_tag) - if upstream_tag not in OVERLAP_TAGS: + if not active_source_carries(upstream_tag): return - patch_path, preimage, postimage = overlap_identity(upstream_tag) - source = source_root / merger_source(upstream_tag) + source = source_root / MERGER_SOURCE digest = source_sha256(source.read_bytes()) - if digest == postimage: + if digest == ASR_POSTIMAGE: return - if digest != preimage: + if digest != ASR_PREIMAGE: raise RuntimeError("ASR merger source changed; requalify untimed overlap patch") - patch_file = BRIDGE_PACKAGE_ROOT / "bridge" / Path(patch_path).name + patch_file = BRIDGE_PACKAGE_ROOT / "bridge" / Path(ASR_PATCH_PATH).name command = ["git", "apply", "--ignore-space-change", str(patch_file)] # Apply from the extracted root, including roots nested in a worktree. # The preimage hash and git apply's check precede any source mutation. subprocess.run([*command[:2], "--check", *command[2:]], check=True, cwd=source_root) subprocess.run(command, check=True, cwd=source_root) - if source_sha256(source.read_bytes()) != postimage: + if source_sha256(source.read_bytes()) != ASR_POSTIMAGE: raise RuntimeError("ASR merger postimage mismatch; requalify untimed overlap patch") print("Applied audited untimed ASR overlap patch", flush=True) -def patch_asr_litertlm_container(source_root: Path, upstream_tag: str) -> None: - """Carry upstream's ASR container routing (#77) on the audited v0.18 source.""" - if not require_container_patch_decision(upstream_tag): - return - digests = { - name: source_sha256((source_root / name).read_bytes()) - for name in CONTAINER_PATCH_SOURCES - } - if all(digests[name] == post for name, (_, post) in CONTAINER_PATCH_SOURCES.items()): - return - if any(digests[name] != pre for name, (pre, _) in CONTAINER_PATCH_SOURCES.items()): - raise RuntimeError("ASR engine source changed; requalify .litertlm container patch") - patch_file = BRIDGE_PACKAGE_ROOT / "bridge/asr_litertlm_container.patch" - command = ["git", "apply", "--ignore-space-change", str(patch_file)] - subprocess.run([*command[:2], "--check", *command[2:]], check=True, - cwd=source_root) - subprocess.run(command, check=True, cwd=source_root) - for name, (_, post) in CONTAINER_PATCH_SOURCES.items(): - if source_sha256((source_root / name).read_bytes()) != post: - raise RuntimeError(".litertlm container patch postimage mismatch; requalify") - print("Applied audited ASR .litertlm container routing patch", flush=True) - - def patch_stream_finish_reason(source_root: Path, upstream_tag: str) -> None: - """Report why streamed generation ended (#78) on the audited v0.18 source.""" - if not require_finish_reason_patch_decision(upstream_tag): + """Apply the audited terminal cause reported by the streaming bridge.""" + if not active_source_carries(upstream_tag): return - sources = finish_reason_patch_sources(upstream_tag) + sources = FINISH_REASON_SOURCES digests = { name: source_sha256((source_root / name).read_bytes()) for name in sources @@ -261,7 +191,7 @@ def patch_stream_finish_reason(source_root: Path, upstream_tag: str) -> None: raise RuntimeError( "Decode or conversation source changed; requalify the stream " "finish-reason patch") - patch_file = REPO_ROOT / finish_reason_patch_path(upstream_tag) + patch_file = REPO_ROOT / FINISH_REASON_PATCH_PATH apply_source_patch(source_root, patch_file, ignore_space_change=True) for name, (_, post) in sources.items(): if source_sha256((source_root / name).read_bytes()) != post: @@ -270,64 +200,32 @@ def patch_stream_finish_reason(source_root: Path, upstream_tag: str) -> None: print("Applied audited stream finish-reason patch", flush=True) -def patch_workspace_build(source_root: Path, compatibility_tag: str) -> None: - """Repair the v0.18.1 Bazel WORKSPACE before other WORKSPACE edits.""" - if not require_workspace_build_patch_decision(compatibility_tag): - return - for name, (pre, _) in WORKSPACE_BUILD_PATCH_SOURCES.items(): - if source_sha256((source_root / name).read_bytes()) != pre: - raise RuntimeError( - "Upstream WORKSPACE or .bazelrc changed; requalify the " - "WORKSPACE build repair") - command = ["git", "apply", str(REPO_ROOT / WORKSPACE_BUILD_PATCH_PATH)] - subprocess.run([*command[:2], "--check", *command[2:]], check=True, - cwd=source_root) - subprocess.run(command, check=True, cwd=source_root) - for name, (_, post) in WORKSPACE_BUILD_PATCH_SOURCES.items(): - if source_sha256((source_root / name).read_bytes()) != post: - raise RuntimeError( - "WORKSPACE build repair postimage mismatch; requalify") - print("Applied audited v0.18.1 WORKSPACE build repair", flush=True) - - -def xnnpack_postimages(compatibility_tag: str) -> dict[str, str]: +def xnnpack_postimages() -> dict[str, str]: """Final XNNPACK sources after both patches; the QC4W opt-out applies last.""" return { name: postimage for sources in ( - xnnpack_pf32_sources(compatibility_tag), - xnnpack_qc4w_sources(compatibility_tag), + XNNPACK_PF32_SOURCES, + XNNPACK_QC4W_SOURCES, ) for name, (_, postimage) in sources.items() } -def verify_xnnpack_postimages(source_root: Path, compatibility_tag: str) -> None: +def verify_xnnpack_postimages(source_root: Path) -> None: """Fails unless Bazel compiled the patched XNNPACK sources.""" repository = (source_root / "bazel-out").resolve().parents[2] / "external" / "XNNPACK" - for name, postimage in xnnpack_postimages(compatibility_tag).items(): + for name, postimage in xnnpack_postimages().items(): source = repository / name if not source.is_file() or source_sha256(source.read_bytes()) != postimage: raise RuntimeError("XNNPACK patch postimage mismatch; requalify") print("Verified XNNPACK PF32 rollback and PQS8/QC4W opt-out postimages", flush=True) -def verify_cpu_options_identifier_postimage(source_root: Path) -> None: - """Fails unless Bazel compiled the patched LiteRT CPU options identifier.""" - repository = (source_root / "bazel-out").resolve().parents[2] / "external" / "litert" - for name, (_, postimage) in CPU_OPTIONS_IDENTIFIER_SOURCES.items(): - source = repository / name - if not source.is_file() or source_sha256(source.read_bytes()) != postimage: - raise RuntimeError("LiteRT CPU options identifier postimage mismatch; requalify") - print("Verified LiteRT CPU options identifier postimage", flush=True) - - -def verify_stage_spatial_tensors_postimages( - source_root: Path, compatibility_tag: str = "v0.19.1" -) -> None: +def verify_stage_spatial_tensors_postimages(source_root: Path) -> None: """Fails unless Bazel used the audited LiteRT WebGPU and Vulkan sources.""" repository = (source_root / "bazel-out").resolve().parents[2] / "external" / "litert" - for name, (_, postimage) in stage_spatial_tensors_identity(compatibility_tag)[3].items(): + for name, (_, postimage) in STAGING_SOURCES.items(): source = repository / name if not source.is_file() or source_sha256(source.read_bytes()) != postimage: raise RuntimeError(f"LiteRT spatial tensor staging postimage mismatch for {name}; requalify") @@ -362,6 +260,7 @@ def reject_ambiguous_workspace(source_root: Path) -> None: def download_upstream( upstream_ref: str, compatibility_tag: str, work_dir: Path ) -> Path: + require_source_build(compatibility_tag) archive_path = source_archive_path(work_dir, upstream_ref) url = github_source_archive_url(UPSTREAM_REPO, upstream_ref) print(f"Downloading {url}", flush=True) @@ -378,46 +277,14 @@ def download_upstream( raise RuntimeError(f"Expected one extracted source directory, got {candidates}") source_root = candidates[0] reject_ambiguous_workspace(source_root) - patch_workspace_build(source_root, compatibility_tag) patch_upstream_workspace( source_root, - patch_ios_framework_paths=has_asr_bridge(compatibility_tag), - compatibility_tag=compatibility_tag, - # v0.19.0 carries an equivalent SentencePiece patch of its own. - patch_bpe_null_piece=is_at_least(compatibility_tag, (0, 17, 0)) - and not is_at_least(compatibility_tag, (0, 19, 0)), - patch_gpu_environment_teardown=needs_gpu_environment_teardown_patch( - (source_root / "WORKSPACE").read_text(encoding="utf-8"), - compatibility_tag, - ), - patch_xnnpack_pf32_sme2=require_xnnpack_pf32_patch_decision(compatibility_tag), - patch_cpu_options_identifier=require_cpu_options_identifier_patch_decision( - compatibility_tag - ), - patch_stage_spatial_tensors=require_stage_spatial_tensors_patch_decision( - compatibility_tag - ), + patch_xnnpack_pf32_sme2=True, + patch_stage_spatial_tensors=True, ) return source_root -def needs_gpu_environment_teardown_patch( - workspace_text: str, compatibility_tag: str -) -> bool: - # The decision follows the pinned LiteRT commit, not the LiteRT-LM version: - # a development build of a later upstream commit keeps the 0.17 - # compatibility tag but already pins a LiteRT with the reordering. - matches = re.findall( - r'^LITERT_REF = "([0-9a-f]{40})"$', workspace_text, re.MULTILINE - ) - if not matches: - if is_at_least(compatibility_tag, (0, 17, 0)): - raise RuntimeError("Expected a pinned LITERT_REF in the upstream WORKSPACE") - return False - # Starlark uses the last assignment; v0.18.1 keeps its old pin above it. - return matches[-1] in LITERT_REFS_WITHOUT_GPU_TEARDOWN_ORDERING - - def verify_litert_archive_pin(workspace: str, ref: str, sha256: str, carry: str) -> None: archive = list(re.finditer( r'^http_archive\(\n name = "litert",\n(.*?)^\)$', @@ -443,38 +310,20 @@ def verify_litert_archive_pin(workspace: str, ref: str, sha256: str, carry: str) raise RuntimeError(f"Unexpected LiteRT archive {name} for {carry}; requalify") -def verify_carried_dependency_pins( - source_root: Path, compatibility_tag: str, *, - spatial_staging: bool, cpu_options: bool, xnnpack: bool, -) -> None: +def verify_carried_dependency_pins(source_root: Path, compatibility_tag: str) -> None: reject_ambiguous_workspace(source_root) - if not (spatial_staging or cpu_options or xnnpack): - return workspace = (source_root / "WORKSPACE").read_text(encoding="utf-8") - if spatial_staging: - _, litert_ref, archive_sha256, _ = stage_spatial_tensors_identity(compatibility_tag) - verify_litert_archive_pin( - workspace, litert_ref, archive_sha256, "LiteRT spatial tensor staging", - ) - if cpu_options: - verify_litert_archive_pin( - workspace, CPU_OPTIONS_LITERT_REF, CPU_OPTIONS_LITERT_ARCHIVE_SHA256, - "LiteRT CPU options identifier rollback", - ) - if xnnpack: - verify_patched_xnnpack_archive(workspace, compatibility_tag) + verify_litert_archive_pin( + workspace, STAGING_LITERT_REF, STAGING_LITERT_SHA256, "LiteRT spatial tensor staging", + ) + verify_patched_xnnpack_archive(workspace, compatibility_tag) def patch_upstream_workspace( source_root: Path, *, - patch_ios_framework_paths: bool = True, - patch_bpe_null_piece: bool = False, - patch_gpu_environment_teardown: bool = False, patch_xnnpack_pf32_sme2: bool = False, - patch_cpu_options_identifier: bool = False, patch_stage_spatial_tensors: bool = False, - compatibility_tag: str = "v0.19.1", ) -> None: workspace = source_root / "WORKSPACE" text = workspace.read_text(encoding="utf-8") @@ -494,18 +343,11 @@ def patch_upstream_workspace( else: text = text.replace(needle, replacement) litert_patches = [] - if patch_ios_framework_paths and not is_at_least(compatibility_tag, (0, 20, 0)): - litert_patches.append("litert_ios_framework_paths.patch") - if patch_gpu_environment_teardown: - litert_patches.append("litert_gpu_environment_destroy_callback.patch") - if patch_cpu_options_identifier: - litert_patches.append("litert_cpu_options_identifier.patch") if patch_stage_spatial_tensors: - patch_path, litert_ref, archive_sha256, _ = stage_spatial_tensors_identity(compatibility_tag) verify_litert_archive_pin( - text, litert_ref, archive_sha256, "LiteRT spatial tensor staging", + text, STAGING_LITERT_REF, STAGING_LITERT_SHA256, "LiteRT spatial tensor staging", ) - litert_patches.append(Path(patch_path).name) + litert_patches.append(Path(STAGING_PATCH_PATH).name) litert_archive = 'http_archive(\n name = "litert",\n' litert_archive_with_patch = ( litert_archive @@ -520,13 +362,11 @@ def patch_upstream_workspace( if litert_archive + " patch_args" in text: raise RuntimeError(f"Unexpected LiteRT patches in {workspace}") text = text.replace(litert_archive, litert_archive_with_patch, 1) - if patch_bpe_null_piece: - text = patch_sentencepiece_bpe_null(text) if patch_xnnpack_pf32_sme2: text = declare_patched_xnnpack(text) workspace.write_text(text, encoding="utf-8") print( - "Patched upstream WORKSPACE dependency URLs and iOS framework paths", + "Patched upstream WORKSPACE dependencies", flush=True, ) @@ -535,7 +375,7 @@ def patch_windows_rules_android(source_root: Path) -> None: workspace = source_root / "WORKSPACE" text = workspace.read_text(encoding="utf-8") refs = re.findall(r'^TENSORFLOW_REF[ \t]*=[ \t]*"([0-9a-f]{40})"$', text, re.MULTILINE) - if refs != [V020_TENSORFLOW_REF]: + if refs != [TENSORFLOW_REF]: raise RuntimeError("TensorFlow pin changed; requalify the Windows rules_android patch") # TensorFlow skips repos declared before tf_workspace2(). Use its archive @@ -563,50 +403,6 @@ def patch_windows_rules_android(source_root: Path) -> None: workspace.write_text(text.replace(hook, "\n" + archive + hook, 1), encoding="utf-8") -def patch_sentencepiece_bpe_null(text: str) -> str: - """Preserve legacy BPE NUL IDs only against the audited SentencePiece archive.""" - pattern = r'http_archive\(\n name = "sentencepiece",\n.*?\n\)' - matches = list(re.finditer(pattern, text, re.DOTALL)) - if len(matches) != 1: - raise RuntimeError("Expected exactly one SentencePiece archive") - match = matches[0] - block = match.group() - for expected in ( - 'sha256 = "92381f713e094a15a1ccff1ac4a5315a4c4b82a99ac1332d6ac53c9dc8e1bcf1"', - 'strip_prefix = "sentencepiece-0.2.2"', - 'url = "https://github.com/google/sentencepiece/archive/refs/tags/v0.2.2.tar.gz"', - ): - if expected not in block: - raise RuntimeError("SentencePiece source changed; requalify BPE NUL compatibility") - patch = (' patch_args = ["-p1"],\n' - ' patches = ["@//bridge:sentencepiece_bpe_null.patch"],\n') - if patch in block: - return text - if re.search(r"\b(?:patches|patch_args)\s*=", block): - raise RuntimeError("Unexpected SentencePiece patches; requalify compatibility") - block = block.replace(' name = "sentencepiece",\n', - ' name = "sentencepiece",\n' + patch, 1) - return text[:match.start()] + block + text[match.end():] - - -def patch_upstream_ios_sampler_path(source_root: Path) -> None: - sampler = source_root / "runtime" / "components" / "sampler_factory.cc" - text = sampler.read_text(encoding="utf-8") - original = '"libLiteRtTopKMetalSampler.dylib"' - replacement = ( - '"@executable_path/Frameworks/LiteRtTopKMetalSampler.framework/' - 'LiteRtTopKMetalSampler"' - ) - if replacement in text: - return - if text.count(original) != 1: - raise RuntimeError( - f"Expected one Metal sampler library path in {sampler}" - ) - sampler.write_text(text.replace(original, replacement), encoding="utf-8") - print("Patched upstream iOS Metal sampler framework path", flush=True) - - def bazel_command() -> list[str]: if shutil.which("bazelisk"): return ["bazelisk"] @@ -669,28 +465,17 @@ def build_runtime( jobs: str | None, upstream_ref: str | None = None, ) -> Path: - patch_stage_spatial_tensors = require_stage_spatial_tensors_patch_decision(upstream_tag) - patch_cpu_options_identifier = require_cpu_options_identifier_patch_decision(upstream_tag) - patch_xnnpack = require_xnnpack_pf32_patch_decision(upstream_tag) - verify_carried_dependency_pins( - source_root, upstream_tag, spatial_staging=patch_stage_spatial_tensors, - cpu_options=patch_cpu_options_identifier, xnnpack=patch_xnnpack, - ) - if platform == "windows" and upstream_tag == "v0.20.0": + require_source_build(upstream_tag) + verify_carried_dependency_pins(source_root, upstream_tag) + if platform == "windows": patch_windows_rules_android(source_root) patch_asr_untimed_overlap(source_root, upstream_tag) - patch_asr_litertlm_container(source_root, upstream_tag) patch_stream_finish_reason(source_root, upstream_tag) patch_huggingface_token_bytes(source_root, upstream_tag) - patch_step_zero_state(source_root, upstream_tag) - if platform == "windows" and require_windows_engine_fd_patch_decision(upstream_tag): + if platform == "windows": patch_windows_engine_fd(source_root, upstream_tag) else: apply_android_gpu_safety(source_root, upstream_tag) - # v0.19.0 removed the prebuilt TopK sampler this path points at. - if (platform == "ios" and has_asr_bridge(upstream_tag) - and not is_at_least(upstream_tag, (0, 19, 0))): - patch_upstream_ios_sampler_path(source_root) prebuilt_target = PREBUILT_TARGETS.get((platform, arch)) if prebuilt_target is not None: source_dir = source_root / "prebuilt" / prebuilt_target @@ -706,8 +491,6 @@ def build_runtime( f"{platform}/{arch}", flush=True, ) - if patch_cpu_options_identifier: - verify_dynamic_runtime(source_root / "prebuilt", platform, arch) target = RUNTIME_TARGETS[(platform, arch)] configs = [ f"--config={config}" @@ -729,30 +512,19 @@ def build_runtime( *configs, *target.get("bazel_options", []), target["bazel_target"], - ("--define=litert_runtime_link_mode=dynamic" - if uses_shared_desktop_litert(platform, upstream_tag) - else "--define=litert_link_capi_so=true"), + "--define=litert_link_capi_so=true", "--define=resolve_symbols_in_exec=false", + "--define=litert_lm_stream_chunk_api=true", + "--define=litert_lm_capabilities_in_c_engine=true", + "--define=litert_lm_asr_api=true", + "--define=litert_lm_asr_omni_engine=true", + "--define=litert_lm_c_api_v1=true", + "--define=litert_lm_in_process_litert=true", ] - if uses_stream_chunk_api(upstream_tag): - command.append("--define=litert_lm_stream_chunk_api=true") - if is_at_least(upstream_tag, (0, 17, 0)): - command.append("--define=litert_lm_capabilities_in_c_engine=true") - if has_asr_bridge(upstream_tag): - command.append("--define=litert_lm_asr_api=true") - if has_omni_asr_engine(upstream_tag): - command.append("--define=litert_lm_asr_omni_engine=true") - if uses_c_api_v1(upstream_tag): - command.append("--define=litert_lm_c_api_v1=true") - if in_process_litert_abi_version(upstream_tag) == 1: - command.append("--define=litert_lm_in_process_litert=true") - if platform == "android" and is_at_least(upstream_tag, (0, 20, 0)): + if platform == "android": command.extend(("--//runtime/executor:gpu_accelerator=webgpu", "--define=litert_lm_android_opencl_sampler=true")) - elif platform == "android" and not has_prebuilt_topk_samplers(upstream_tag): - command.append("--define=litert_lm_android_webgpu_sampler=true") - if require_finish_reason_patch_decision(upstream_tag): - command.append(FINISH_REASON_DEFINE) + command.append(FINISH_REASON_DEFINE) if platform == "macos": command.append(f"--macos_minimum_os={MACOS_MINIMUM_OS}") if platform == "ios": @@ -762,34 +534,22 @@ def build_runtime( command.append("--ios_minimum_os=13.0") if jobs: command.append(f"--jobs={jobs}") - pins = {} - if patch_stage_spatial_tensors: - _, litert_ref, archive_sha256, _ = stage_spatial_tensors_identity(upstream_tag) - pins["litert"] = (archive_sha256, f"LiteRT-{litert_ref}") - if patch_cpu_options_identifier: - pins["litert"] = (CPU_OPTIONS_LITERT_ARCHIVE_SHA256, f"LiteRT-{CPU_OPTIONS_LITERT_REF}") - if patch_xnnpack: - pins["XNNPACK"] = (xnnpack_archive_sha256(upstream_tag), f"XNNPACK-{xnnpack_commit(upstream_tag)}") - - if pins: - workspace_rc = source_root / ".bazelrc" - rc_text = workspace_rc.read_text(encoding="utf-8") if workspace_rc.is_file() else "" - with tempfile.TemporaryDirectory(prefix="litert-bazel-") as temp: - config = Path(temp) / "release.bazelrc" - config.write_text(release_workspace_rc(rc_text), encoding="utf-8") - startup.extend(("--noworkspace_rc", f"--bazelrc={bazel_path(config)}")) - # Keep both commands in the WORKSPACE mode used by the pin verifier. - command.append("--noenable_bzlmod") - fetch_audited_archives(startup, source_root, bridge_options, Path(temp) / "resolved.bzl", pins) - run([*startup, *command], source_root) - else: + pins = { + "litert": (STAGING_LITERT_SHA256, f"LiteRT-{STAGING_LITERT_REF}"), + "XNNPACK": (XNNPACK_SHA256, f"XNNPACK-{XNNPACK_COMMIT}"), + } + workspace_rc = source_root / ".bazelrc" + rc_text = workspace_rc.read_text(encoding="utf-8") if workspace_rc.is_file() else "" + with tempfile.TemporaryDirectory(prefix="litert-bazel-") as temp: + config = Path(temp) / "release.bazelrc" + config.write_text(release_workspace_rc(rc_text), encoding="utf-8") + startup.extend(("--noworkspace_rc", f"--bazelrc={bazel_path(config)}")) + # Keep both commands in the WORKSPACE mode used by the pin verifier. + command.append("--noenable_bzlmod") + fetch_audited_archives(startup, source_root, bridge_options, Path(temp) / "resolved.bzl", pins) run([*startup, *command], source_root) - if patch_xnnpack: - verify_xnnpack_postimages(source_root, upstream_tag) - if patch_cpu_options_identifier: - verify_cpu_options_identifier_postimage(source_root) - if patch_stage_spatial_tensors: - verify_stage_spatial_tensors_postimages(source_root, upstream_tag) + verify_xnnpack_postimages(source_root) + verify_stage_spatial_tensors_postimages(source_root) if "output" in target: output = source_root / target["output"] @@ -1117,6 +877,11 @@ def validate_runtime(output: Path, platform: str, upstream_tag: str) -> None: validate_android_gpu_environment_teardown(output, platform) +def require_source_build(compatibility_tag: str) -> None: + if not active_source_carries(compatibility_tag): + raise RuntimeError("Use the historical native release ref to build LiteRT-LM before v0.20.0") + + def main() -> int: parser = argparse.ArgumentParser( description=f"Build the upstream {UPSTREAM_REPO} C runtime library." @@ -1136,6 +901,7 @@ def main() -> int: parser.add_argument("--jobs") args = parser.parse_args() upstream_ref = args.upstream_ref or args.upstream_tag + require_source_build(args.upstream_tag) key = (args.platform, args.arch) if key == ("macos", "x64"): diff --git a/tools/fixtures/asr_engine_v018.cc b/tools/fixtures/asr_engine_v018.cc deleted file mode 100644 index 34550d2..0000000 --- a/tools/fixtures/asr_engine_v018.cc +++ /dev/null @@ -1,347 +0,0 @@ -// Copyright 2026 The ODML Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "omni/asr/asr_engine.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "absl/status/status.h" // from @com_google_absl -#include "absl/status/status_macros.h" // from @com_google_absl -#include "absl/status/statusor.h" // from @com_google_absl -#include "absl/strings/match.h" // from @com_google_absl -#include "absl/strings/str_cat.h" // from @com_google_absl -#include "absl/strings/string_view.h" // from @com_google_absl -#include "litert/cc/litert_buffer_ref.h" // from @litert -#include "litert/cc/litert_common.h" // from @litert -#include "litert/cc/litert_compiled_model.h" // from @litert -#include "litert/cc/litert_environment.h" // from @litert -#include "litert/cc/litert_macros.h" // from @litert -#include "litert/cc/litert_options.h" // from @litert -#include "litert/cc/options/litert_cpu_options.h" // from @litert -#include "litert/cc/options/litert_gpu_options.h" // from @litert -#include "litert/cc/options/litert_qualcomm_options.h" // from @litert -#include "omni/asr/asr_session.h" -#include "omni/asr/audio_preprocessor.h" -#include "omni/asr/audio_source.h" -#include "omni/asr/ctc_decoder.h" -#include "omni/asr/dummy_preprocessor.h" -#include "omni/asr/levenshtein_text_merger.h" -#include "omni/asr/litert_speech_recognizer.h" -#include "omni/asr/lm_decoder.h" -#include "omni/asr/lm_engine_decoder.h" -#include "omni/asr/log_mel_spectrogram_processor.h" -#include "omni/asr/stateless_decoder.h" -#include "omni/asr/tdt_decoder.h" -#include "omni/asr/text_merger.h" -#include "omni/asr/timestamp_text_merger.h" -#include "omni/asr/tokenizer_detokenizer.h" -#include "omni/base/litert_lm_engine_runner.h" -#include "omni/base/litert_lm_runner.h" -#include "omni/base/litert_runner.h" -#include "omni/base/model_utils.h" -#include "runtime/components/model_resources.h" -#include "runtime/executor/executor_settings_base.h" -#include "runtime/framework/threadpool.h" -#include "support/tokenizer/huggingface_tokenizer.h" -#include "support/tokenizer/tokenizer.h" - -namespace litert::omni::asr { -namespace { - -constexpr absl::string_view kDefaultPrompt = - "Transcribe the following speech segment: "; -constexpr int kDefaultMaxOutputTokens = 128; - -bool FileExists(absl::string_view path) { - std::ifstream f(std::string(path).c_str()); - return f.good(); -} - -} // namespace - -absl::Status AsrEngine::EnsureFilesDownloaded( - AsrEngineConfig& config, const FileDownloader& downloader) { - if (!config.model_url.empty() && !FileExists(config.model_path)) { - if (!downloader) { - return absl::NotFoundError(absl::StrCat("Model file missing at ", - config.model_path, - " and no downloader provided.")); - } - ABSL_RETURN_IF_ERROR(downloader(config.model_url, config.model_path)); - } - if (!config.tokenizer_url.empty() && !FileExists(config.tokenizer_path)) { - if (!downloader) { - return absl::NotFoundError(absl::StrCat("Tokenizer file missing at ", - config.tokenizer_path, - " and no downloader provided.")); - } - ABSL_RETURN_IF_ERROR( - downloader(config.tokenizer_url, config.tokenizer_path)); - } - return absl::OkStatus(); -} - -absl::StatusOr> AsrEngine::Create( - AsrEngineConfig config, FileDownloader downloader) { - ABSL_RETURN_IF_ERROR(EnsureFilesDownloaded(config, downloader)); - - LITERT_ASSIGN_OR_RETURN(auto environment, ::litert::Environment::Create({})); - LITERT_ASSIGN_OR_RETURN(auto options, ::litert::Options::Create()); - uint32_t accelerators = static_cast(::litert::HwAccelerators::kCpu); - if (config.num_threads > 0) { - LITERT_ASSIGN_OR_RETURN(auto& cpu_options, - options.GetOptions<::litert::CpuOptions>()); - cpu_options.SetNumThreads(config.num_threads); - } - if (config.backend == AsrEngineConfig::Backend::kGpu) { - accelerators |= static_cast(::litert::HwAccelerators::kGpu); - LITERT_ASSIGN_OR_RETURN(auto& gpu_options, - options.GetOptions<::litert::GpuOptions>()); - gpu_options.SetPrecision(::litert::GpuOptions::Precision::kFp32); - gpu_options.EnableConstantTensorSharing(true); - for (const auto& pattern : config.state_buffer_name_patterns) { - gpu_options.AddExternalTensorPattern(pattern.c_str()); - gpu_options.AddBufferStorageTensorPattern(pattern.c_str()); - } - } else if (config.backend == AsrEngineConfig::Backend::kNpu) { - accelerators |= static_cast(::litert::HwAccelerators::kNpu); - LITERT_ASSIGN_OR_RETURN( - auto& qnn_options, - options.GetOptions<::litert::qualcomm::QualcommOptions>()); - qnn_options.SetHtpPerformanceMode(::litert::qualcomm::QualcommOptions:: - HtpPerformanceMode::kHighPerformance); - } - LITERT_RETURN_IF_ERROR(options.SetHardwareAccelerators( - static_cast<::litert::HwAccelerators>(accelerators))); - - auto thread_pool = std::make_unique<::litert::lm::ThreadPool>( - "asr_engine_pool", config.num_threads); - - bool use_litert_lm = - config.decoder_type == AsrEngineConfig::DecoderType::kLm || - absl::EndsWith(config.model_path, ".litertlm"); - if (!use_litert_lm) { - ABSL_ASSIGN_OR_RETURN( - auto tokenizer, ::litert::support::HuggingFaceTokenizer::CreateFromFile( - config.tokenizer_path)); - if (config.vocab_size == 0) { - config.vocab_size = tokenizer->GetVocabSize(); - } - - LITERT_ASSIGN_OR_RETURN(auto compiled_model, - ::litert::CompiledModel::Create( - environment, config.model_path, options)); - - return std::unique_ptr(new AsrEngine( - std::move(config), std::move(tokenizer), - std::make_unique<::litert::Environment>(std::move(environment)), - std::make_unique<::litert::CompiledModel>(std::move(compiled_model)), - std::move(thread_pool))); - } - - config.decoder_type = AsrEngineConfig::DecoderType::kLm; - - ModelOptions lm_options; - if (config.backend == AsrEngineConfig::Backend::kGpu) { - lm_options.backend = lm::Backend::GPU; - } else if (config.backend == AsrEngineConfig::Backend::kNpu) { - lm_options.backend = lm::Backend::NPU; - } else { - lm_options.backend = lm::Backend::CPU; - } - lm_options.num_threads = config.num_threads; - lm_options.cache_dir = config.cache_dir; - - // Models requiring mel normalization (e.g. multimodal speech-language - // models) use the end-to-end LiteRT-LM Engine which integrates the audio - // frontend and LLM, whereas other models use the modular executor-based - // runner. - bool use_engine = config.log_mel_config.normalize_mel; - - std::unique_ptr lm_runner; - std::unique_ptr lm_engine_runner; - std::unique_ptr<::litert::CompiledModel> compiled_model; - - if (use_engine) { - ABSL_ASSIGN_OR_RETURN( - lm_engine_runner, - CreateLmEngineRunner(environment, lm_options, config.model_path)); - } else { - ABSL_ASSIGN_OR_RETURN( - lm_runner, CreateLmRunner(environment, lm_options, config.model_path)); - - auto* model_resources = lm_runner->mutable_model_resources(); - if (model_resources == nullptr) { - return absl::InternalError("ModelResources not available in LmRunner."); - } - - ABSL_ASSIGN_OR_RETURN(auto audio_model_flatbuffer, - model_resources->GetTFLiteModelBuffer( - lm::ModelType::kTfLiteAudioEncoderHw)); - LITERT_ASSIGN_OR_RETURN( - auto comp_model, - ::litert::CompiledModel::Create( - environment, - ::litert::BufferRef( - reinterpret_cast(audio_model_flatbuffer.data()), - audio_model_flatbuffer.size()), - options)); - compiled_model = - std::make_unique<::litert::CompiledModel>(std::move(comp_model)); - } - - lm::ModelResources* model_resources = nullptr; - if (lm_engine_runner != nullptr) { - model_resources = lm_engine_runner->mutable_model_resources(); - } else if (lm_runner != nullptr) { - model_resources = lm_runner->mutable_model_resources(); - } - if (model_resources == nullptr) { - return absl::InternalError("ModelResources not available in runner."); - } - ABSL_ASSIGN_OR_RETURN(auto tokenizer, model_resources->GetTokenizer()); - if (config.vocab_size == 0) { - config.vocab_size = tokenizer->GetVocabSize(); - } - - return std::unique_ptr(new AsrEngine( - std::move(config), std::move(tokenizer), - std::make_unique<::litert::Environment>(std::move(environment)), - std::move(compiled_model), std::move(thread_pool), std::move(lm_runner), - std::move(lm_engine_runner))); -} - -AsrEngine::AsrEngine(AsrEngineConfig config, - std::unique_ptr<::litert::support::Tokenizer> tokenizer, - std::unique_ptr<::litert::Environment> environment, - std::unique_ptr<::litert::CompiledModel> compiled_model, - std::unique_ptr<::litert::lm::ThreadPool> thread_pool, - std::unique_ptr lm_runner, - std::unique_ptr lm_engine_runner) - : config_(std::move(config)), - tokenizer_(std::move(tokenizer)), - environment_(std::move(environment)), - compiled_model_(std::move(compiled_model)), - thread_pool_(std::move(thread_pool)), - lm_runner_(std::move(lm_runner)), - lm_engine_runner_(std::move(lm_engine_runner)) {} - -absl::StatusOr> AsrEngine::CreateSession( - std::unique_ptr audio_source) { - std::unique_ptr runner; - if (compiled_model_ != nullptr) { - runner = std::make_unique(compiled_model_.get()); - } else { - const size_t buffer_size_bytes = config_.log_mel_config.n_frames * - config_.log_mel_config.n_mels * - sizeof(float); - runner = std::make_unique( - std::vector{buffer_size_bytes}); - } - - AudioSource* raw_audio_source = audio_source.get(); - std::unique_ptr preprocessor; - if (config_.has_log_mel_config) { - ABSL_ASSIGN_OR_RETURN( - preprocessor, - LogMelSpectrogramProcessor::Create( - config_.sample_rate_hz, config_.log_mel_config, raw_audio_source)); - } else { - preprocessor = std::make_unique(raw_audio_source); - } - - std::unique_ptr decoder; - switch (config_.decoder_type) { - case AsrEngineConfig::DecoderType::kTdt: { - ABSL_ASSIGN_OR_RETURN( - decoder, - TdtDecoder::Create(runner.get(), config_.decode_start_token_id, - config_.decode_statefully_after)); - break; - } - case AsrEngineConfig::DecoderType::kCtc: { - ABSL_ASSIGN_OR_RETURN(decoder, CtcDecoder::Create(config_.vocab_size)); - break; - } - case AsrEngineConfig::DecoderType::kStateless: { - ABSL_ASSIGN_OR_RETURN( - decoder, - StatelessDecoder::Create( - runner.get(), config_.decode_start_token_id, - config_.decode_stop_token_id, - config_.decode_skip_until_token_id)); - break; - } - case AsrEngineConfig::DecoderType::kLm: { - if (lm_engine_runner_ != nullptr) { - ABSL_ASSIGN_OR_RETURN( - decoder, LmEngineDecoder::Create( - lm_engine_runner_.get(), std::string(kDefaultPrompt), - kDefaultMaxOutputTokens, config_.decode_start_token_id, - config_.decode_stop_token_id, - config_.decode_skip_until_token_id)); - } else if (lm_runner_ != nullptr) { - ABSL_ASSIGN_OR_RETURN( - decoder, - LmDecoder::Create(lm_runner_.get(), config_.decode_start_token_id, - config_.decode_stop_token_id, - config_.decode_skip_until_token_id)); - } else { - return absl::InternalError( - "LmDecoder requested but neither lm_runner_ nor " - "lm_engine_runner_ is available."); - } - break; - } - } - - AudioPreprocessor* raw_preprocessor = preprocessor.get(); - ABSL_ASSIGN_OR_RETURN( - auto speech_recognizer, - LiteRtSpeechRecognizer::Create(std::move(runner), raw_preprocessor, - std::move(decoder))); - - LiteRtSpeechRecognizer* raw_speech_recognizer = speech_recognizer.get(); - auto detokenizer = std::make_unique( - raw_speech_recognizer, tokenizer_.get()); - - TokenizerDetokenizer* raw_detokenizer = detokenizer.get(); - std::unique_ptr text_merger; - switch (config_.text_merger_type) { - case AsrEngineConfig::TextMergerType::kLevenshtein: - text_merger = std::make_unique(raw_detokenizer); - break; - case AsrEngineConfig::TextMergerType::kTimestamp: - text_merger = std::make_unique( - raw_detokenizer, config_.overlap_ratio); - break; - } - - AsrSession::Components components; - components.audio_source = std::move(audio_source); - components.preprocessor = std::move(preprocessor); - components.speech_recognizer = std::move(speech_recognizer); - components.detokenizer = std::move(detokenizer); - components.text_merger = std::move(text_merger); - - return AsrSession::Create(std::move(components), thread_pool_.get()); -} - -} // namespace litert::omni::asr diff --git a/tools/fixtures/asr_engine_v018.h b/tools/fixtures/asr_engine_v018.h deleted file mode 100644 index 7028a56..0000000 --- a/tools/fixtures/asr_engine_v018.h +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2026 The ODML Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef THIRD_PARTY_ODML_LITERT_LM_OMNI_ASR_ASR_ENGINE_H_ -#define THIRD_PARTY_ODML_LITERT_LM_OMNI_ASR_ASR_ENGINE_H_ - -#include -#include - -#include "absl/functional/any_invocable.h" // from @com_google_absl -#include "absl/status/status.h" // from @com_google_absl -#include "absl/status/statusor.h" // from @com_google_absl -#include "absl/strings/string_view.h" // from @com_google_absl -#include "litert/cc/litert_compiled_model.h" // from @litert -#include "litert/cc/litert_environment.h" // from @litert -#include "omni/asr/asr_session.h" -#include "omni/asr/audio_source.h" -#include "omni/asr/log_mel_spectrogram_processor.h" -#include "omni/base/litert_lm_engine_runner.h" -#include "omni/base/litert_lm_runner.h" -#include "runtime/framework/threadpool.h" -#include "support/tokenizer/tokenizer.h" - -namespace litert::omni::asr { - -struct AsrEngineConfig { - enum class DecoderType { - kCtc = 0, - kTdt = 1, - kStateless = 2, - kLm = 3, - }; - - enum class Backend { - kCpu = 0, - kGpu = 1, - kNpu = 2, - }; - - enum class TextMergerType { - kLevenshtein = 0, - kTimestamp = 1, - }; - - std::string model_name; - std::string model_path; - std::string tokenizer_path; - std::string model_url; - std::string tokenizer_url; - - int sample_rate_hz = 16000; - int input_milliseconds = 5000; - - DecoderType decoder_type = DecoderType::kTdt; - Backend backend = Backend::kCpu; - TextMergerType text_merger_type = TextMergerType::kTimestamp; - int num_threads = 4; - float overlap_ratio = 0.4f; - - bool has_log_mel_config = false; - LogMelSpectrogramProcessor::LogMelSpectrogramConfig log_mel_config; - - int decode_start_token_id = -1; - int decode_stop_token_id = -1; - int decode_skip_until_token_id = -1; - int decode_statefully_after = 4; - int vocab_size = 0; - int blank_token_id = 0; - - // Patterns for state and intermediate buffer tensor names (e.g., recurrent - // states, encoder outputs) to be declared as external tensors for GPU - // (ml_drift). - std::vector state_buffer_name_patterns; - - std::string cache_dir = "/tmp/asr_models"; -}; - -// Engine that manages model loading, tokenizer instantiation, and ASR session -// creation. -class AsrEngine { - public: - using FileDownloader = absl::AnyInvocable; - - // Creates an AsrEngine. Downloads missing model/tokenizer files using - // downloader callback. - static absl::StatusOr> Create( - AsrEngineConfig config, FileDownloader downloader = nullptr); - - ~AsrEngine() = default; - - // Instantiates components based on configuration and returns a new - // AsrSession. - absl::StatusOr> CreateSession( - std::unique_ptr audio_source); - - const AsrEngineConfig& config() const { return config_; } - - private: - AsrEngine(AsrEngineConfig config, - std::unique_ptr<::litert::support::Tokenizer> tokenizer, - std::unique_ptr<::litert::Environment> environment, - std::unique_ptr<::litert::CompiledModel> compiled_model, - std::unique_ptr<::litert::lm::ThreadPool> thread_pool, - std::unique_ptr lm_runner = nullptr, - std::unique_ptr lm_engine_runner = nullptr); - - static absl::Status EnsureFilesDownloaded(AsrEngineConfig& config, - const FileDownloader& downloader); - - AsrEngineConfig config_; - std::unique_ptr<::litert::support::Tokenizer> tokenizer_; - std::unique_ptr<::litert::Environment> environment_; - std::unique_ptr<::litert::CompiledModel> compiled_model_; - std::unique_ptr<::litert::lm::ThreadPool> thread_pool_; - std::unique_ptr lm_runner_; - std::unique_ptr lm_engine_runner_; -}; - -} // namespace litert::omni::asr - -#endif // THIRD_PARTY_ODML_LITERT_LM_OMNI_ASR_ASR_ENGINE_H_ diff --git a/tools/fixtures/litert_lm_v0.17.0_workspace_excerpt.txt b/tools/fixtures/litert_lm_v0.17.0_workspace_excerpt.txt deleted file mode 100644 index 4b0257a..0000000 --- a/tools/fixtures/litert_lm_v0.17.0_workspace_excerpt.txt +++ /dev/null @@ -1,56 +0,0 @@ -# buildifier: disable=load-on-top - -workspace(name = "litert_lm") - -# UPDATED = 2026-08-27 -LITERT_REF = "9fe5be45564c868408e6514c8aabb83e211a0911" - -LITERT_SHA256 = "5dbb113744e103f899c7b1b7c5479126b36a0b7414c3d971185c1f02041bfa39" - -TENSORFLOW_REF = "d9a8da74b4c3de28a39ab34ad007838d6bc30c67" - -TENSORFLOW_SHA256 = "cd46b37c0f722d5a48c0accc9618cc5684c553332b913091023703461f318d9b" - -# Same one downloaded by tensorflow, but refer contrib/minizip. -http_archive( - name = "minizip", - add_prefix = "minizip", - build_file = "@//:BUILD.minizip", - sha256 = "9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23", - strip_prefix = "zlib-1.3.1/contrib/minizip", - urls = [ - "https://storage.googleapis.com/mirror.tensorflow.org/zlib.net/fossils/zlib-1.3.1.tar.gz", - "https://mirror.bazel.build/zlib.net/fossils/zlib-1.3.1.tar.gz", - "https://zlib.net/fossils/zlib-1.3.1.tar.gz", - ], -) - -http_archive( - name = "sentencepiece", - build_file = "@//:BUILD.sentencepiece", - patch_cmds = [ - "printf '#ifndef CONFIG_H_\\n#define CONFIG_H_\\n#define VERSION \"0.2.2\"\\n#define PACKAGE \"sentencepiece\"\\n#define PACKAGE_STRING \"sentencepiece\"\\n#define INSTALL_DATADIR \"\"\\n#endif\\n' > config.h", - "mv src/* .", - # Replace third_party/absl/ with absl/ in *.h and *.cc files. - "sed -i -e 's|#include \"third_party/absl/|#include \"absl/|g' *.h *.cc", - # Replace third_party/protobuf-lite/ with google/protobuf/ in *.h and *.cc files. - "sed -i -e 's|#include \"third_party/protobuf-lite/google/protobuf/|#include \"google/protobuf/|g' *.h *.cc", - "sed -i -e 's|#include \"third_party/protobuf/|#include \"google/protobuf/|g' *.h *.cc", - "rm -rf third_party/protobuf-lite third_party/protobuf third_party/absl third_party/abseil-cpp", - ], - sha256 = "92381f713e094a15a1ccff1ac4a5315a4c4b82a99ac1332d6ac53c9dc8e1bcf1", - strip_prefix = "sentencepiece-0.2.2", - url = "https://github.com/google/sentencepiece/archive/refs/tags/v0.2.2.tar.gz", -) - -http_archive( - name = "litert", - patch_cmds = [ - # Replace @//third_party with @litert//third_party in files under third_party/. - "sed -i -e 's|\"@//third_party/|\"@litert//third_party/|g' third_party/*/*", - ], - sha256 = LITERT_SHA256, - strip_prefix = "LiteRT-" + LITERT_REF, - url = "https://github.com/google-ai-edge/LiteRT/archive/" + LITERT_REF + ".tar.gz", -) - diff --git a/tools/fixtures/litert_lm_v0.18.0_workspace_excerpt.txt b/tools/fixtures/litert_lm_v0.18.0_workspace_excerpt.txt deleted file mode 100644 index 4a269e8..0000000 --- a/tools/fixtures/litert_lm_v0.18.0_workspace_excerpt.txt +++ /dev/null @@ -1,59 +0,0 @@ -# Exact LiteRT-LM b2f686e2ed4718fb84ec398a61dd59ca0f0aff27 WORKSPACE excerpts. -# Apache-2.0; Copyright 2026 Google LLC. -# buildifier: disable=load-on-top - -workspace(name = "litert_lm") - -# UPDATED = 2026-09-25 -LITERT_REF = "26895c9fbcc25c43faa8c1a98cd1fd28951602c3" - -LITERT_SHA256 = "698811a8ec56f6a9bd7705ffaa75ff792cae03a67d3a759dbc84f2023493ee6f" - -# Keep TensorFlow at this commit for now. Newer commits load -# `compatibility_proxy_repo` from `@rules_cc//cc:extensions.bzl` in -# `tensorflow/workspace1.bzl`, which the rules_cc version resolved by this -# WORKSPACE does not provide, breaking the bazel build (as of 2026-09-15). -http_archive( - name = "minizip", - add_prefix = "minizip", - build_file = "@//third_party/minizip:minizip.BUILD", - sha256 = "9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23", - strip_prefix = "zlib-1.3.1/contrib/minizip", - urls = [ - "https://storage.googleapis.com/mirror.tensorflow.org/zlib.net/fossils/zlib-1.3.1.tar.gz", - "https://mirror.bazel.build/zlib.net/fossils/zlib-1.3.1.tar.gz", - "https://zlib.net/fossils/zlib-1.3.1.tar.gz", - ], -) - -http_archive( - name = "sentencepiece", - build_file = "@//third_party/sentencepiece:sentencepiece.BUILD", - patch_cmds = [ - "printf '#ifndef CONFIG_H_\\n#define CONFIG_H_\\n#define VERSION \"0.2.2\"\\n#define PACKAGE \"sentencepiece\"\\n#define PACKAGE_STRING \"sentencepiece\"\\n#define INSTALL_DATADIR \"\"\\n#endif\\n' > config.h", - "mv src/* .", - # Replace third_party/absl/ with absl/ in *.h and *.cc files. - "sed -i -e 's|#include \"third_party/absl/|#include \"absl/|g' *.h *.cc", - # Replace third_party/protobuf-lite/ with google/protobuf/ in *.h and *.cc files. - "sed -i -e 's|#include \"third_party/protobuf-lite/google/protobuf/|#include \"google/protobuf/|g' *.h *.cc", - "sed -i -e 's|#include \"third_party/protobuf/|#include \"google/protobuf/|g' *.h *.cc", - "rm -rf third_party/protobuf-lite third_party/protobuf third_party/absl third_party/abseil-cpp", - ], - sha256 = "92381f713e094a15a1ccff1ac4a5315a4c4b82a99ac1332d6ac53c9dc8e1bcf1", - strip_prefix = "sentencepiece-0.2.2", - url = "https://github.com/google/sentencepiece/archive/refs/tags/v0.2.2.tar.gz", -) - -http_archive( - name = "litert", - patch_cmds = [ - # Replace @//third_party with @litert//third_party in files under third_party/. - # Only regular files are passed to `sed -i`, which fails on directories such as - # third_party/py/numpy. Uses a shell loop rather than `find`, which may resolve - # to find.exe on Windows. - "for f in third_party/*/*; do if [ -f \"$f\" ]; then sed -i -e 's|\"@//third_party/|\"@litert//third_party/|g' \"$f\" || exit 1; fi; done", - ], - sha256 = LITERT_SHA256, - strip_prefix = "LiteRT-" + LITERT_REF, - url = "https://github.com/google-ai-edge/LiteRT/archive/" + LITERT_REF + ".tar.gz", -) diff --git a/tools/fixtures/litert_lm_v0.18.1.bazelrc b/tools/fixtures/litert_lm_v0.18.1.bazelrc deleted file mode 100644 index 301143a..0000000 --- a/tools/fixtures/litert_lm_v0.18.1.bazelrc +++ /dev/null @@ -1,541 +0,0 @@ -# LiteRT Bazel configuration file. -# This file tries to group and simplify build options for LiteRT -# -# ----CONFIG OPTIONS---- -# Android options: -# android: -# android_arm: -# android_arm64: -# android_x86: -# android_x86_64: -# -# iOS options: -# ios: -# ios_armv7: -# ios_arm64: -# ios_x86_64: -# ios_fat: -# -# Macosx options -# darwin_arm64: -# -# Compiler options: -# avx_linux: Build with avx instruction set on linux. -# avx_win: Build with avx instruction set on windows -# -# Other build options: -# short_logs: Only log errors during build, skip warnings. -# verbose_logs: Show all compiler warnings during build. -# monolithic: Build all TF C++ code into a single shared object. -# dynamic_kernels: Try to link all kernels dynamically (experimental). -# dbg: Build with debug info -# -# TF version options; -# v2: Build TF v2 -# -# Embedded Linux options (experimental and only tested with TFLite build yet) -# elinux: General Embedded Linux options shared by all flavors. -# elinux_aarch64: Embedded Linux options for aarch64 (ARM64) CPU support. -# elinux_armhf: Embedded Linux options for armhf (ARMv7) CPU support. -# -# Default build options. These are applied first and unconditionally. - -# Exclude OpenCL from Linux and Windows builds. -build:linux --copt=-DLITERT_DISABLE_OPENCL_SUPPORT=1 -build:windows --copt=/DLITERT_DISABLE_OPENCL_SUPPORT=1 - -build --repo_env=USE_PYWRAP_RULES=True -build --copt=-DGRPC_BAZEL_BUILD -build --host_copt=-DGRPC_BAZEL_BUILD -build --action_env=GRPC_BAZEL_RUNTIME=1 -build --repo_env=PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=upb -build --action_env=PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=upb - -# Some targets have the same py source file, but use different -# configurations via `requires-` tags. This results in an action -# conflict when precompiling. Disable to avoid that problem. -# See https://github.com/bazel-contrib/rules_python/issues/2445 -build --@rules_python//python/config_settings:precompile=force_disabled - -# Do not do this. This is how gRPC builds itself by default, but we don't want -# that as it would link protobuf into its own set of dynamic libraries, which -# would conflict with our protobuf linkage. -#build --define=use_fast_cpp_protos=true - -# For projects which use TensorFlow as part of a Bazel build process, putting -# nothing in a bazelrc will default to a monolithic build. The following line -# opts in to modular op registration support by default. -build --define framework_shared_object=true -build --define tsl_protobuf_header_only=true - -build --define=allow_oversize_protos=true -# protobuf will stop supporting MSVC. -build:windows --define=protobuf_allow_msvc=true - -build --spawn_strategy=standalone -build -c opt - -# Make Bazel print out all options from rc files. -build --announce_rc - -# TODO(mihaimaruseac): Document this option or remove if no longer needed -build --define=grpc_no_ares=true - -# Disable legacy whole archive so that cc_binary(..., linkshared = 1) targets -# do not wrap all transitive static archives (such as Rust's -# libprofiler_builtins) in -Wl,-whole-archive. See b/469455895. -build --legacy_whole_archive=0 - -# TODO(mihaimaruseac): Document this option or remove if no longer needed -build --enable_platform_specific_config - -# Enable XLA support by default. -build --define=with_xla_support=true - -# TODO(mihaimaruseac): Document this option or remove if no longer needed -build --config=short_logs - -# TF now has `cc_shared_library` targets, so it needs the experimental flag -# TODO(rostam): Remove when `cc_shared_library` is enabled by default -build --experimental_cc_shared_library - -# cc_shared_library ensures no library is linked statically more than once. -build --experimental_link_static_libraries_once=false - -# Prevent regressions on those two incompatible changes -# TODO: remove those flags when they are flipped in the default Bazel version TF uses. -build --incompatible_enforce_config_setting_visibility -# TODO: also enable this flag after fixing the visibility violations -# build --incompatible_config_setting_private_default_visibility - -# Disable Hermetic CC toolchains -build --@rules_ml_toolchain//common:enable_hermetic_cc=False -build --repo_env USE_HERMETIC_CC_TOOLCHAIN=0 -# Hermetic python version -build --repo_env=HERMETIC_PYTHON_VERSION=3.13 - -# Default options should come above this line. - -# Enforce clang as C/C++ compiler on Linux. -build:linux --action_env=CC=clang -build:linux --action_env=CXX=clang++ - -# Android configs. Bazel needs to have --cpu and --fat_apk_cpu both set to the -# target CPU to build transient dependencies correctly. See -# https://docs.bazel.build/versions/master/user-manual.html#flag--fat_apk_cpu -build:android --crosstool_top=//external:android/crosstool -build:android --host_crosstool_top=@bazel_tools//tools/cpp:toolchain -build:android_arm --config=android -build:android_arm --cpu=armeabi-v7a -build:android_arm --fat_apk_cpu=armeabi-v7a -build:android_arm --platforms=@org_tensorflow//tensorflow/tools/toolchains/android:armeabi-v7a -build:android_arm64 --config=android -build:android_arm64 --cpu=arm64-v8a -build:android_arm64 --fat_apk_cpu=arm64-v8a -build:android_arm64 --platforms=@org_tensorflow//tensorflow/tools/toolchains/android:arm64-v8a -build:android_x86 --config=android -build:android_x86 --cpu=x86 -build:android_x86 --fat_apk_cpu=x86 -build:android_x86 --platforms=@org_tensorflow//tensorflow/tools/toolchains/android:x86 -build:android_x86_64 --config=android -build:android_x86_64 --cpu=x86_64 -build:android_x86_64 --fat_apk_cpu=x86_64 -build:android_x86_64 --platforms=@org_tensorflow//tensorflow/tools/toolchains/android:x86_64 - -# Build everything statically for Android since all static libs are later -# bundled together into a single .so for deployment. -build:android --dynamic_mode=off -# TODO(belitskiy): Remove once on Clang 20. -build:android --define=xnn_enable_avxvnniint8=false -# Ensure OpenCL is not inadvertently disabled when cross-compiling from a Linux host. -build:android --copt=-ULITERT_DISABLE_OPENCL_SUPPORT - -# Sets the default Apple platform to macOS. -build:macos --apple_platform_type=macos - -# gRPC on MacOS requires this #define -build:macos --copt=-DGRPC_BAZEL_BUILD - -# Avoid hitting command line argument limit -build:macos --features=archive_param_file - -# Bazel 7.0.0 no longer supports dynamic symbol lookup on macOS. To resolve -# undefined symbol errors in macOS arm64 builds, explicitly add the necessary -# linker flags until dependencies are well defined. See -# https://github.com/bazelbuild/bazel/issues/19730. -build:macos --linkopt=-Wl,-undefined,dynamic_lookup -build:macos --host_linkopt=-Wl,-undefined,dynamic_lookup - -# Settings for MacOS on ARM CPUs. -build:macos_arm64 --cpu=darwin_arm64 -build:macos_arm64 --macos_minimum_os=11.0 -build:macos_arm64 --platforms=@build_bazel_apple_support//platforms:darwin_arm64 - -# iOS configs for each architecture and the fat binary builds. -build:ios --apple_platform_type=ios -# build:ios --copt=-fembed-bitcode -build:ios --copt=-Wno-c++11-narrowing -build:ios --ios_minimum_os=13.0 -build:ios_armv7 --config=ios -build:ios_armv7 --cpu=ios_armv7 -build:ios_armv7 --platforms=@org_tensorflow//tensorflow/tools/toolchains/ios:ios_armv7 -build:ios_arm64 --config=ios -build:ios_arm64 --cpu=ios_arm64 -build:ios_arm64 --platforms=@build_bazel_apple_support//platforms:ios_arm64 -build:ios_arm64e --config=ios -build:ios_arm64e --cpu=ios_arm64e -build:ios_arm64e --platforms=@build_bazel_apple_support//platforms:ios_arm64e -build:ios_sim_arm64 --config=ios -build:ios_sim_arm64 --cpu=ios_sim_arm64 -build:ios_sim_arm64 --platforms=@build_bazel_apple_support//platforms:ios_sim_arm64 -build:ios_x86_64 --config=ios -build:ios_x86_64 --cpu=ios_x86_64 -build:ios_x86_64 --platforms=@build_bazel_apple_support//platforms:ios_x86_64 -build:ios_fat --config=ios -build:ios_fat --ios_multi_cpus=armv7,arm64,i386,x86_64 - -# Config to use a mostly-static build and disable modular op registration -# support (this will revert to loading TensorFlow with RTLD_GLOBAL in Python). -# By default, TensorFlow will build with a dependence on -# //tensorflow:libtensorflow_framework.so. -build:monolithic --define framework_shared_object=false -build:monolithic --define tsl_protobuf_header_only=false -build:monolithic --experimental_link_static_libraries_once=false # b/229868128 - -# Debug config -build:dbg -c dbg -# Only include debug info for files under tensorflow/, excluding kernels, to -# reduce the size of the debug info in the binary. This is because if the debug -# sections in the ELF binary are too large, errors can occur. See -# https://github.com/tensorflow/tensorflow/issues/48919. -# Users can still include debug info for a specific kernel, e.g. with: -# --config=dbg --per_file_copt=+tensorflow/core/kernels/identity_op.*@-g -# Since this .bazelrc file is synced between the tensorflow/tensorflow repo and -# the openxla/xla repo, also include debug info for files under xla/. -build:dbg --per_file_copt=+.*,-tensorflow.*,-xla.*@-g0 -build:dbg --per_file_copt=+tensorflow/core/kernels.*@-g0 -# for now, disable arm_neon. see: https://github.com/tensorflow/tensorflow/issues/33360 -build:dbg --cxxopt -DTF_LITE_DISABLE_X86_NEON -# AWS SDK must be compiled in release mode. see: https://github.com/tensorflow/tensorflow/issues/37498 -build:dbg --copt -DDEBUG_BUILD - -# Options to disable default on features -build:nogcp --define=no_gcp_support=true -build:nonccl --define=no_nccl_support=true - -# Modular TF build options -build:dynamic_kernels --define=dynamic_loaded_kernels=true -build:dynamic_kernels --copt=-DAUTOLOAD_DYNAMIC_KERNELS - - -# Suppress all C++ compiler warnings, otherwise build logs become 10s of MBs. -build:android --copt=-w -build:ios --copt=-w -build:linux --host_copt=-w -build:macos --copt=-w -build:windows --copt=/W0 -build:windows --host_copt=/W0 - -# Suppress most C++ compiler warnings to reduce log size but allow -# for specific warnings to still be present. -build:linux --copt="-Wno-all" -build:linux --copt="-Wno-extra" -build:linux --copt="-Wno-deprecated" -build:linux --copt="-Wno-deprecated-declarations" -build:linux --copt="-Wno-ignored-attributes" -build:linux --copt="-Wno-array-bounds" - -# Add unused-result as an error on Linux. -build:linux --copt="-Wunused-result" -build:linux --copt="-Werror=unused-result" -# Add switch as an error on Linux. -build:linux --copt="-Wswitch" -build:linux --copt="-Werror=switch" -# Suppress switch-default warnings on Linux. Skia has a lot of these. -build:linux --copt="-Wno-switch-default" -# This was added in clang-16 by https://reviews.llvm.org/D133574. -# Can be removed once upb is updated, since a type definition is used within -# offset of in the current version of ubp. -# See https://github.com/protocolbuffers/upb/blob/9effcbcb27f0a665f9f345030188c0b291e32482/upb/upb.c#L183. -build:linux --copt=-Wno-gnu-offsetof-extensions - -# Toolchain and CUDA options for Linux CPU builds -build:release_cpu_linux --crosstool_top="@local_config_cuda//crosstool:toolchain" -build:release_cpu_linux --repo_env=TF_SYSROOT="/dt9" - -# Linux ARM64 specific options -build:linux_arm64 --copt="-mtune=generic" --copt="-march=armv8-a" --copt="-O3" -build:linux_arm64 --define=litert_enable_ynnpack=true - -# On Windows, `__cplusplus` is wrongly defined without this switch -# See https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/ -build:windows --copt=/Zc:__cplusplus -build:windows --host_copt=/Zc:__cplusplus - -# Tensorflow uses M_* math constants that only get defined by MSVC headers if -# _USE_MATH_DEFINES is defined. -build:windows --copt=/D_USE_MATH_DEFINES -build:windows --host_copt=/D_USE_MATH_DEFINES - -# Windows has a relatively short command line limit, which TF has begun to hit. -# See https://docs.bazel.build/versions/main/windows.html -build:windows --features=compiler_param_file -build:windows --features=archive_param_file - -# Speed Windows compile times. Available in VS 16.4 (we are on 16.11). See -# https://groups.google.com/a/tensorflow.org/d/topic/build/SsW98Eo7l3o/discussion -build:windows --copt=/d2ReducedOptimizeHugeFunctions -build:windows --host_copt=/d2ReducedOptimizeHugeFunctions - -# Before VS 2017 15.8, the member "type" would non-conformingly have an -# alignment of only alignof(max_align_t). VS 2017 15.8 was fixed to handle this -# correctly, but the fix inherently changes layout and breaks binary -# compatibility (*only* for uses of aligned_storage with extended alignments). -build:windows --copt=-D_ENABLE_EXTENDED_ALIGNED_STORAGE -build:windows --host_copt=-D_ENABLE_EXTENDED_ALIGNED_STORAGE - -# Enable the runfiles symlink tree on Windows. This makes it possible to build -# the pip package on Windows without an intermediate data-file archive, as the -# build_pip_package script in its current form (as of Aug 2023) uses the -# runfiles symlink tree to decide what to put into the Python wheel. -startup --windows_enable_symlinks -build:windows --enable_runfiles - -# Default paths for TF_SYSTEM_LIBS -build:linux --define=PREFIX=/usr -build:linux --define=LIBDIR=$(PREFIX)/lib -build:linux --define=INCLUDEDIR=$(PREFIX)/include -build:linux --define=PROTOBUF_INCLUDE_PATH=$(PREFIX)/include -build:macos --define=PREFIX=/usr -build:macos --define=LIBDIR=$(PREFIX)/lib -build:macos --define=INCLUDEDIR=$(PREFIX)/include -build:macos --define=PROTOBUF_INCLUDE_PATH=$(PREFIX)/include -# TF_SYSTEM_LIBS do not work on windows. - -# By default, build TF in C++ 20 mode. -build:android --cxxopt=-std=c++20 -build:android --host_cxxopt=-std=c++20 -build:ios --cxxopt=-std=c++20 -build:ios --host_cxxopt=-std=c++20 -build:linux --cxxopt=-std=c++20 -build:linux --host_cxxopt=-std=c++20 -build:macos --cxxopt=-std=c++20 -build:macos --host_cxxopt=-std=c++20 -build:windows --cxxopt=/std:c++20 -build:windows --host_cxxopt=/std:c++20 - -# On Windows, set /std:c11 and /experimental:c11atomics for pthreadpool. -build:windows --conlyopt=/std:c11 -build:windows --host_conlyopt=/std:c11 -build:windows --conlyopt=/experimental:c11atomics -build:windows --host_conlyopt=/experimental:c11atomics -build:windows --per_file_copt=external/pthreadpool/.*@-std=c11 -build:windows --per_file_copt=external/pthreadpool/_*@/D_CRT_SECURE_NO_WARNINGS - -# On windows, we still link everything into a single DLL. -build:windows --config=monolithic - -# On linux, we dynamically link small amount of kernels -build:linux --config=dynamic_kernels - -# Make sure to include as little of windows.h as possible -build:windows --copt=-DWIN32_LEAN_AND_MEAN -build:windows --host_copt=-DWIN32_LEAN_AND_MEAN -build:windows --copt=-DNOGDI -build:windows --host_copt=-DNOGDI - -# MSVC (Windows): Standards-conformant preprocessor mode -# See https://docs.microsoft.com/en-us/cpp/preprocessor/preprocessor-experimental-overview -build:windows --copt=/Zc:preprocessor -build:windows --host_copt=/Zc:preprocessor - -# Misc build options we need for windows. -build:windows --linkopt=/DEBUG -build:windows --host_linkopt=/DEBUG -build:windows --linkopt=/OPT:REF -build:windows --host_linkopt=/OPT:REF -build:windows --linkopt=/OPT:ICF -build:windows --host_linkopt=/OPT:ICF - -# Force local execution for genrules on Windows -build:windows --strategy=Genrule=local -build:windows --genrule_strategy=local -build:windows --spawn_strategy=local - -# protobuf can't find its headers on windows when built locally with bazelisk. -build:windows --host_copt=/Iexternal/com_google_protobuf/src - -# Use Git Bash for genrules -build:windows --shell_executable="C:/Program Files/Git/bin/bash.exe" - -# Verbose failure logs when something goes wrong -build:windows --verbose_failures - -# Work around potential issues with large command lines on windows. -# See: https://github.com/bazelbuild/bazel/issues/5163 -build:windows --features=compiler_param_file - -# Do not risk cache corruption. See: -# https://github.com/bazelbuild/bazel/issues/3360 -build:linux --experimental_guard_against_concurrent_changes - -# Configure short or long logs -build:short_logs --output_filter=DONT_MATCH_ANYTHING -build:verbose_logs --output_filter= - -# Instruction set optimizations -# TODO(gunan): Create a feature in toolchains for avx/avx2 to -# avoid having to define linux/win separately. -build:avx_linux --copt=-mavx -build:avx_linux --host_copt=-mavx -build:avx_win --copt=/arch:AVX - -# Assume AVX2 x86_64 platforms for linux and windows. -build:linux_x86_64 --copt=-mavx2 -build:windows --copt=/arch:AVX2 - -# Enable all targets in XLA -build:cpu_cross --define=with_cross_compiler_support=true - -# Disable XLA on mobile. -build:xla --define=with_xla_support=true # TODO: remove, it's on by default. -build:android --define=with_xla_support=false -build:ios --define=with_xla_support=false - -# Enable string absl flags on mobile which is disabled by default. -build:android --copt=-DABSL_FLAGS_STRIP_NAMES=0 -build:ios --copt=-DABSL_FLAGS_STRIP_NAMES=0 - -# Flag to enable remote config -common --experimental_repo_remote_exec - -# Use GitHub mirror for BCR to work around bcr.bazel.build outages -common --registry=https://raw.githubusercontent.com/bazelbuild/bazel-central-registry/main/ - -# TFLite build configs for generic embedded Linux -build:elinux --crosstool_top=@local_config_embedded_arm//:toolchain -build:elinux --host_crosstool_top=@bazel_tools//tools/cpp:toolchain -build:elinux_aarch64 --config=elinux -build:elinux_aarch64 --cpu=aarch64 -build:elinux_armhf --config=elinux -build:elinux_armhf --cpu=armhf -build:elinux_armhf --copt -mfp16-format=ieee - -# Config-specific options should come above this line. - -# Load rc file written by ./configure. -try-import %workspace%/.tf_configure.bazelrc -try-import %workspace%/xla_configure.bazelrc - -# Load rc file with user-specific options. -try-import %workspace%/.bazelrc.user - -# Try to load the XLA warnings config if available -try-import %workspace%/warnings.bazelrc - -# Options to build TensorFlow 1.x or 2.x. -build:v2 --define=tf_api_version=2 --action_env=TF2_BEHAVIOR=1 -build --config=v2 - -# Options to filter filepath prefixes when generating python api's -build:litert_prefixes --define=litert_prefixes="external/org_tensorflow/" -build --config=litert_prefixes - -# Options to disable generating api v2 under tensorflow/lite/python. -# This is not on by default and don't use this flag during wheel generation. -# Remove the flag once tf/lite is fully separated from tf. -build:disable_tf_lite_py --define=disable_tf_lite_py=true - -# Config to use a gcs bucket as remote cache. -build:public_cache --remote_cache="https://storage.googleapis.com/litert-bazel-artifacts" --remote_upload_local_results=false - -# Cache pushes are limited to CI system. -# WARNING: THIS OPTION WONT WORK IF YOU DO NOT HAVE PROPER AUTHENTICATION AND PERMISSIONS -build:public_cache_push --config=public_cache --remote_upload_local_results=true --google_default_credentials - -# BEGIN LITERT REMOTE BUILD EXECUTION OPTIONS -# WARNING: THESE OPTIONS WONT WORK IF YOU DO NOT HAVE PROPER AUTHENTICATION AND PERMISSIONS - -# Allow creation of resultstore URLs for any bazel invocation -build:resultstore --google_default_credentials -build:resultstore --bes_backend=buildeventservice.googleapis.com -build:resultstore --bes_instance_name="tensorflow-testing" -build:resultstore --bes_results_url="https://source.cloud.google.com/results/invocations" -build:resultstore --bes_timeout=600s - -# Flag to enable remote config -common --experimental_repo_remote_exec - -# Make Bazel not try to probe the host system for a C++ toolchain. -build:rbe_base --config=resultstore -build:rbe_base --repo_env=BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1 -build:rbe_base --define=EXECUTOR=remote -build:rbe_base --jobs=200 -build:rbe_base --remote_executor=grpcs://remotebuildexecution.googleapis.com -build:rbe_base --remote_timeout=3600 -build:rbe_base --spawn_strategy=remote,worker,standalone,local - -# Attempt to minimize the amount of data transfer between bazel and the remote -# workers: -build:rbe_base --remote_download_toplevel -test:rbe_base --test_env=USER=anon - -build:rbe_linux --config=rbe_base -build:rbe_linux --action_env=PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/go/bin" -# Non-rbe settings we should include because we do not run configure -build:rbe_linux --config=avx_linux -build:rbe_linux --linkopt=-lrt -build:rbe_linux --host_linkopt=-lrt -build:rbe_linux --linkopt=-lm -build:rbe_linux --host_linkopt=-lm - -build:rbe_linux_cpu --config=rbe_linux - -# Linux cpu and cuda builds share the same toolchain now. -build:rbe_linux_cpu --host_crosstool_top="@local_config_cuda//crosstool:toolchain" -build:rbe_linux_cpu --crosstool_top="@local_config_cuda//crosstool:toolchain" -build:rbe_linux_cpu --extra_toolchains="@local_config_cuda//crosstool:toolchain-linux-x86_64" -build:rbe_linux_cpu --repo_env=CC="/usr/lib/llvm-18/bin/clang" -build:rbe_linux_cpu --extra_execution_platforms="@ml_build_config_platform//:platform" -build:rbe_linux_cpu --host_platform="@ml_build_config_platform//:platform" -build:rbe_linux_cpu --platforms="@ml_build_config_platform//:platform" -# This is needed for all Clang17 builds but must not be present in GCC builds. -build:rbe_linux_cpu --copt=-Wno-error=unused-command-line-argument -# These you may need to change for your own GCP project. -common:rbe_linux_cpu --remote_instance_name=projects/tensorflow-testing/instances/default_instance -# END LITERT REMOTE BUILD EXECUTION OPTIONS - -# Filters used when building in bulk in cpu. -build:bulk_build_cpu --build_tag_filters=-no_oss,-oss_serial,-gpu,-tpu,-v1only -build:bulk_test_cpu --show_timestamps -build:bulk_test_cpu --experimental_ui_max_stdouterr_bytes=3145728 - -# Filters used when testing in bulk in cpu. -test:bulk_test_cpu --config=bulk_build_cpu -test:bulk_test_cpu --test_tag_filters=-no_oss,-oss_serial,-gpu,-tpu,-v1only,-benchmark-test -test:bulk_test_cpu --test_summary=short -test:bulk_test_cpu --test_output=errors -test:bulk_test_cpu --verbose_failures=true -test:bulk_test_cpu --flaky_test_attempts=3 -test:bulk_test_cpu --build_tests_only - -# TODO: b/397625618 Enable bzlmod -common --noenable_bzlmod - -# --- Fix for Clang 19+ and Strict Layering Checks --- -build --features=-layering_check -build --host_features=-layering_check - -build --features=-header_modules -build --host_features=-header_modules - -# TODO : b/501457260 Investigate supporting C++20 by upgrading to glibc 2.35 sysroot in future. -# Hermetic Linux x86_64 build targeting glibc 2.31 (used by Kokoro) -build:hermetic_linux --@rules_ml_toolchain//common:enable_hermetic_cc=True -build:hermetic_linux --repo_env=USE_HERMETIC_CC_TOOLCHAIN=1 -build:hermetic_linux --extra_toolchains=@rules_ml_toolchain//cc:linux_x86_64_linux_x86_64 -build:hermetic_linux --host_crosstool_top=@rules_ml_toolchain//cc:linux_x86_64_linux_x86_64 -build:hermetic_linux --cxxopt=-std=c++17 -build:hermetic_linux --host_cxxopt=-std=c++17 -build:hermetic_linux --repo_env=SYSROOT_DIST=linux_glibc_2_31 - diff --git a/tools/fixtures/litert_lm_v0.18.1_WORKSPACE b/tools/fixtures/litert_lm_v0.18.1_WORKSPACE deleted file mode 100644 index 50a5a92..0000000 --- a/tools/fixtures/litert_lm_v0.18.1_WORKSPACE +++ /dev/null @@ -1,641 +0,0 @@ -# buildifier: disable=load-on-top - -workspace(name = "litert_lm") - -# UPDATED = 2026-09-25 -LITERT_REF = "26895c9fbcc25c43faa8c1a98cd1fd28951602c3" - -LITERT_SHA256 = "698811a8ec56f6a9bd7705ffaa75ff792cae03a67d3a759dbc84f2023493ee6f" - -# Keep TensorFlow at this commit for now. Newer commits load -# `compatibility_proxy_repo` from `@rules_cc//cc:extensions.bzl` in -# `tensorflow/workspace1.bzl`, which the rules_cc version resolved by this -# WORKSPACE does not provide, breaking the bazel build (as of 2026-09-15). -TENSORFLOW_REF = "d9a8da74b4c3de28a39ab34ad007838d6bc30c67" - -TENSORFLOW_SHA256 = "cd46b37c0f722d5a48c0accc9618cc5684c553332b913091023703461f318d9b" - -# UPDATED = 2026-10-09 -LITERT_REF = "ca21dc99de51c76bdcc572afeea1dd937d3c9e5c" - -LITERT_SHA256 = "d3c0455b405fadc597c840c8d708ced4f2a89c78eae21d9c0252f744b94c7fbc" - -TENSORFLOW_REF = "a1179d3c224967bd979950b823d5ce2a7e8f4c94" - -TENSORFLOW_SHA256 = "c99256ecac35ee2d7795de8ee8976afbcc47308edf2c8a04a20a5bd8ffd5b8ae" - -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") - -http_archive( - name = "rules_shell", - sha256 = "bc61ef94facc78e20a645726f64756e5e285a045037c7a61f65af2941f4c25e1", - strip_prefix = "rules_shell-0.4.1", - url = "https://github.com/bazelbuild/rules_shell/releases/download/v0.4.1/rules_shell-v0.4.1.tar.gz", -) - -load("@rules_shell//shell:repositories.bzl", "rules_shell_dependencies", "rules_shell_toolchains") - -rules_shell_dependencies() - -rules_shell_toolchains() - -http_archive( - name = "rules_platform", - sha256 = "0aadd1bd350091aa1f9b6f2fbcac8cd98201476289454e475b28801ecf85d3fd", - url = "https://github.com/bazelbuild/rules_platform/releases/download/0.1.0/rules_platform-0.1.0.tar.gz", -) - -# Use recent platoforms version to support uefi platform. -http_archive( - name = "platforms", - sha256 = "3384eb1c30762704fbe38e440204e114154086c8fc8a8c2e3e28441028c019a8", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/1.0.0/platforms-1.0.0.tar.gz", - "https://github.com/bazelbuild/platforms/releases/download/1.0.0/platforms-1.0.0.tar.gz", - ], -) - -# Use 3.22.0 (from 3.5.1 of tensorflow) to fix binary signing issue on MacOS Tahoe. -http_archive( - name = "build_bazel_rules_apple", - sha256 = "a78f26c22ac8d6e3f3fcaad50eace4d9c767688bd7254b75bdf4a6735b299f6a", - url = "https://github.com/bazelbuild/rules_apple/releases/download/3.22.0/rules_apple.3.22.0.tar.gz", -) - -load( - "@build_bazel_rules_apple//apple:repositories.bzl", - "apple_rules_dependencies", -) - -apple_rules_dependencies() - -http_archive( - name = "build_bazel_rules_swift", - sha256 = "f7a67197cd8a79debfe70b8cef4dc19d03039af02cc561e31e0718e98cad83ac", - url = "https://github.com/bazelbuild/rules_swift/releases/download/2.9.0/rules_swift.2.9.0.tar.gz", -) - -# Lower the version from 1.24.5 that tensorflow uses to 1.23.1, the highest version which don't have -# issues with missing LC_UUID, DEVELOPER_DIR or SDKROOT on MacOS Tahoe. -http_archive( - name = "build_bazel_apple_support", - sha256 = "ee20cc5c0bab47065473c8033d462374dd38d172406ecc8de5c8f08487943f2f", - url = "https://github.com/bazelbuild/apple_support/releases/download/1.23.1/apple_support.1.23.1.tar.gz", -) - -http_archive( - name = "bazel_features", - sha256 = "c26b4e69cf02fea24511a108d158188b9d8174426311aac59ce803a78d107648", - strip_prefix = "bazel_features-1.43.0", - url = "https://github.com/bazel-contrib/bazel_features/releases/download/v1.43.0/bazel_features-v1.43.0.tar.gz", -) - -# Same version that tensorflow uses, but with patches to fix build errors. -http_archive( - name = "com_google_absl", - patch_cmds = [ - # Replace @googletest with @com_google_googletest. - "sed -i -e 's|@googletest|@com_google_googletest|g' absl/*/BUILD* absl/*/*/BUILD* absl/*/*/*/BUILD*", - ], - patches = ["@//third_party/abseil:abseil.patch"], - sha256 = "6e1aee535473414164bf83e4ebc40240dec71a4701f8a642d906e95bea1aea0c", - strip_prefix = "abseil-cpp-20260526.0", - url = "https://github.com/abseil/abseil-cpp/archive/20260526.0.tar.gz", -) - -# Toolchains for ML projects -# Older version than one tensorflow uses as current tensorflow breaks workspace build. -# Details: https://github.com/google-ml-infra/rules_ml_toolchain -http_archive( - name = "rules_ml_toolchain", - sha256 = "3b05687842427041c65d1bc2f4aeda3a3079557120f5be8c34690087a88c5de5", - strip_prefix = "rules_ml_toolchain-2eddbc595cc0bbe650c2640204f66b14f015f1a8", - url = "https://github.com/google-ml-infra/rules_ml_toolchain/archive/2eddbc595cc0bbe650c2640204f66b14f015f1a8.tar.gz", -) - -# Kotlin rules (must be declared before tf_workspace to override) -http_archive( - name = "rules_kotlin", - sha256 = "e40ccc013f874e063bb64fed0f816b881991cb300bce45085e1204644892c59c", - url = "https://github.com/bazel-contrib/rules_kotlin/releases/download/v2.4.10/rules_kotlin-v2.4.10.tar.gz", -) - -# Go rules and Gazelle for rules_android (must be declared before tf_workspace to override ancient versions) -http_archive( - name = "io_bazel_rules_go", - sha256 = "68af54cb97fbdee5e5e8fe8d210d15a518f9d62abfd71620c3eaff3b26a5ff86", - urls = [ - "https://mirror.bazel.build/github.com/bazel-contrib/rules_go/releases/download/v0.59.0/rules_go-v0.59.0.zip", - "https://github.com/bazel-contrib/rules_go/releases/download/v0.59.0/rules_go-v0.59.0.zip", - ], -) - -http_archive( - name = "bazel_gazelle", - sha256 = "675114d8b433d0a9f54d81171833be96ebc4113115664b791e6f204d58e93446", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.47.0/bazel-gazelle-v0.47.0.tar.gz", - "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.47.0/bazel-gazelle-v0.47.0.tar.gz", - ], -) - -load("@io_bazel_rules_go//go:deps.bzl", "go_rules_dependencies") - -go_rules_dependencies() - -# TensorFlow -http_archive( - name = "org_tensorflow", - patches = ["@//third_party/tensorflow:tensorflow.patch"], - sha256 = TENSORFLOW_SHA256, - strip_prefix = "tensorflow-" + TENSORFLOW_REF, - url = "https://github.com/tensorflow/tensorflow/archive/" + TENSORFLOW_REF + ".tar.gz", -) - -# Initialize the TensorFlow repository and all dependencies. -# -# The cascade of load() statements and tf_workspace?() calls works around the -# restriction that load() statements need to be at the top of .bzl files. -# E.g. we can not retrieve a new repository with http_archive and then load() -# a macro from that repository in the same file. -load("@org_tensorflow//tensorflow:workspace3.bzl", "tf_workspace3") - -tf_workspace3() - -load( - "@rules_ml_toolchain//cc/deps:cc_toolchain_deps.bzl", - "cc_toolchain_deps", -) - -cc_toolchain_deps() - -# Initialize hermetic Python -load("@xla//third_party/py:python_init_rules.bzl", "python_init_rules") - -python_init_rules() - -load("@xla//third_party/py:python_init_repositories.bzl", "python_init_repositories") - -python_init_repositories( - default_python_version = "system", - requirements = { - "3.10": "@org_tensorflow//:requirements_lock_3_10.txt", - "3.11": "@org_tensorflow//:requirements_lock_3_11.txt", - "3.12": "@org_tensorflow//:requirements_lock_3_12.txt", - "3.13": "@org_tensorflow//:requirements_lock_3_13.txt", - "3.14": "@org_tensorflow//:requirements_lock_3_14.txt", - }, -) - -load("@xla//third_party/py:python_init_toolchains.bzl", "python_init_toolchains") - -python_init_toolchains() - -load("@xla//third_party/py:python_init_pip.bzl", "python_init_pip") - -python_init_pip() - -load("@pypi//:requirements.bzl", "install_deps") - -install_deps() -# End hermetic Python initialization - -RULES_JVM_EXTERNAL_TAG = "6.8" - -RULES_JVM_EXTERNAL_SHA = "704a0197e4e966f96993260418f2542568198490456c21814f647ae7091f56f2" - -http_archive( - name = "rules_jvm_external", - sha256 = RULES_JVM_EXTERNAL_SHA, - strip_prefix = "rules_jvm_external-%s" % RULES_JVM_EXTERNAL_TAG, - url = "https://github.com/bazelbuild/rules_jvm_external/releases/download/%s/rules_jvm_external-%s.tar.gz" % (RULES_JVM_EXTERNAL_TAG, RULES_JVM_EXTERNAL_TAG), -) - -load("@rules_jvm_external//:defs.bzl", "maven_install") - -maven_install( - name = "maven", - artifacts = [ - "com.google.code.gson:gson:2.14.0", - "org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.11.0", - "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0", - ], - repositories = [ - "https://maven.google.com", - "https://repo1.maven.org/maven2", - ], -) - -load("@org_tensorflow//tensorflow:workspace2.bzl", "tf_workspace2") - -tf_workspace2() - -load("@org_tensorflow//tensorflow:workspace1.bzl", "tf_workspace1") - -tf_workspace1() - -load("@org_tensorflow//tensorflow:workspace0.bzl", "tf_workspace0") - -tf_workspace0() - -load( - "@xla//third_party/py:python_wheel.bzl", - "python_wheel_version_suffix_repository", -) - -python_wheel_version_suffix_repository(name = "tf_wheel_version_suffix") - -load( - "@rules_ml_toolchain//gpu/cuda:cuda_json_init_repository.bzl", - "cuda_json_init_repository", -) - -cuda_json_init_repository() - -load( - "@cuda_redist_json//:distributions.bzl", - "CUDA_REDISTRIBUTIONS", - "CUDNN_REDISTRIBUTIONS", -) -load( - "@rules_ml_toolchain//gpu/cuda:cuda_redist_init_repositories.bzl", - "cuda_redist_init_repositories", - "cudnn_redist_init_repository", -) - -cuda_redist_init_repositories( - cuda_redistributions = CUDA_REDISTRIBUTIONS, -) - -cudnn_redist_init_repository( - cudnn_redistributions = CUDNN_REDISTRIBUTIONS, -) - -load( - "@rules_ml_toolchain//gpu/cuda:cuda_configure.bzl", - "cuda_configure", -) - -cuda_configure(name = "local_config_cuda") - -load( - "@rules_ml_toolchain//gpu/nccl:nccl_redist_init_repository.bzl", - "nccl_redist_init_repository", -) - -nccl_redist_init_repository() - -load( - "@rules_ml_toolchain//gpu/nccl:nccl_configure.bzl", - "nccl_configure", -) - -nccl_configure(name = "local_config_nccl") - -# Kotlin rules - -load("@rules_kotlin//kotlin:repositories.bzl", "kotlin_repositories") - -kotlin_repositories() # if you want the default. Otherwise see custom kotlinc distribution below - -load("@rules_kotlin//kotlin:core.bzl", "kt_register_toolchains") - -kt_register_toolchains() # to use the default toolchain, otherwise see toolchains below - -# Rust (for HuggingFace Tokenizers) -http_archive( - name = "rules_rust", - patches = ["@//third_party/rules_rust:rules_rust.patch"], - sha256 = "53c1bac7ec48f7ce48c4c1c6aa006f27515add2aeb05725937224e6e00ec7cea", - url = "https://github.com/bazelbuild/rules_rust/releases/download/0.61.0/rules_rust-0.61.0.tar.gz", -) - -load("@rules_rust//rust:repositories.bzl", "rules_rust_dependencies", "rust_register_toolchains") - -rules_rust_dependencies() - -rust_register_toolchains( - edition = "2021", - extra_target_triples = [ - # Explicitly add toolchains for mobile. Desktop platforms are supported by default. - "aarch64-linux-android", - "aarch64-apple-ios", - "aarch64-apple-ios-sim", - "x86_64-linux-android", - "x86_64-apple-darwin", - ], -) - -load("@rules_rust//crate_universe:repositories.bzl", "crate_universe_dependencies") - -crate_universe_dependencies() - -load("@rules_rust//crate_universe:defs.bzl", "crate", "crates_repository") -load("@rules_rust//rust/platform:triple_mappings.bzl", "SUPPORTED_PLATFORM_TRIPLES") - -# NOTE: llguidance's build file and the llguidance/toktrie patches below live at -# the repository root rather than under third_party/ with the other dependencies. -# rules_rust hashes these label strings into the checked-in cargo-bazel-lock.json, -# so renaming them requires re-pinning the lockfile with -# `CARGO_BAZEL_REPIN=1 bazel sync --only=crate_index`. -crates_repository( - name = "crate_index", - annotations = { - "llguidance": [ - crate.annotation( - additive_build_file = "@//:BUILD.llguidance", - gen_build_script = False, - patches = [ - "@//:PATCH.llguidance_regexvec", - "@//:PATCH.llguidance_numeric", - "@//:PATCH.llguidance_grammar", - "@//:PATCH.llguidance_parser", - "@//:PATCH.llguidance_perf", - ], - ), - ], - "toktrie": [ - crate.annotation( - patches = ["@//:PATCH.toktrie"], - ), - ], - }, - cargo_lockfile = "//:Cargo.lock", - lockfile = "//:cargo-bazel-lock.json", - manifests = [ - "//:Cargo.toml", - ], - supported_platform_triples = SUPPORTED_PLATFORM_TRIPLES + [ - "x86_64-linux-android", - ], -) - -load("@crate_index//:defs.bzl", "crate_repositories") - -crate_repositories() - -# cxxbridge-cmd is a binary-only package so we follow the steps in -# https://bazelbuild.github.io/rules_rust/crate_universe_workspace.html#binary-dependencies. -http_archive( - name = "cxxbridge_cmd", - build_file = "//cxxbridge_cmd:BUILD.cxxbridge_cmd.bazel", - integrity = "sha256-pf/3kWu94FwtuZRp8J3PryA78lsJbMv052GgR5JBLhA=", - strip_prefix = "cxxbridge-cmd-1.0.149", - type = "tar.gz", - url = "https://static.crates.io/crates/cxxbridge-cmd/cxxbridge-cmd-1.0.149.crate", -) - -crates_repository( - name = "cxxbridge_cmd_deps", - cargo_lockfile = "//cxxbridge_cmd:Cargo.lock", - manifests = ["@cxxbridge_cmd//:Cargo.toml"], -) - -load("@cxxbridge_cmd_deps//:defs.bzl", cxxbridge_cmd_deps = "crate_repositories") - -cxxbridge_cmd_deps() - -# Same one downloaded by tensorflow, but refer contrib/minizip. -http_archive( - name = "minizip", - add_prefix = "minizip", - build_file = "@//third_party/minizip:minizip.BUILD", - sha256 = "9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23", - strip_prefix = "zlib-1.3.1/contrib/minizip", - urls = [ - "https://storage.googleapis.com/mirror.tensorflow.org/zlib.net/fossils/zlib-1.3.1.tar.gz", - "https://mirror.bazel.build/zlib.net/fossils/zlib-1.3.1.tar.gz", - "https://zlib.net/fossils/zlib-1.3.1.tar.gz", - ], -) - -http_archive( - name = "sentencepiece", - build_file = "@//third_party/sentencepiece:sentencepiece.BUILD", - patch_cmds = [ - "printf '#ifndef CONFIG_H_\\n#define CONFIG_H_\\n#define VERSION \"0.2.2\"\\n#define PACKAGE \"sentencepiece\"\\n#define PACKAGE_STRING \"sentencepiece\"\\n#define INSTALL_DATADIR \"\"\\n#endif\\n' > config.h", - "mv src/* .", - # Replace third_party/absl/ with absl/ in *.h and *.cc files. - "sed -i -e 's|#include \"third_party/absl/|#include \"absl/|g' *.h *.cc", - # Replace third_party/protobuf-lite/ with google/protobuf/ in *.h and *.cc files. - "sed -i -e 's|#include \"third_party/protobuf-lite/google/protobuf/|#include \"google/protobuf/|g' *.h *.cc", - "sed -i -e 's|#include \"third_party/protobuf/|#include \"google/protobuf/|g' *.h *.cc", - "rm -rf third_party/protobuf-lite third_party/protobuf third_party/absl third_party/abseil-cpp", - ], - sha256 = "92381f713e094a15a1ccff1ac4a5315a4c4b82a99ac1332d6ac53c9dc8e1bcf1", - strip_prefix = "sentencepiece-0.2.2", - url = "https://github.com/google/sentencepiece/archive/refs/tags/v0.2.2.tar.gz", -) - -http_archive( - name = "litert", - patch_cmds = [ - # Replace @//third_party with @litert//third_party in files under third_party/. - # Only regular files are passed to `sed -i`, which fails on directories such as - # third_party/py/numpy. Uses a shell loop rather than `find`, which may resolve - # to find.exe on Windows. - "for f in third_party/*/*; do if [ -f \"$f\" ]; then sed -i -e 's|\"@//third_party/|\"@litert//third_party/|g' \"$f\" || exit 1; fi; done", - ], - sha256 = LITERT_SHA256, - strip_prefix = "LiteRT-" + LITERT_REF, - url = "https://github.com/google-ai-edge/LiteRT/archive/" + LITERT_REF + ".tar.gz", -) - -http_archive( - name = "tokenizers_cpp", - build_file = "@//third_party/tokenizers_cpp:tokenizers_cpp.BUILD", - sha256 = "3e0b9ec325a326b0a2cef5cf164ee94a74ac372c5881ae5af634036db0441823", - strip_prefix = "tokenizers-cpp-0.1.1", - url = "https://github.com/mlc-ai/tokenizers-cpp/archive/refs/tags/v0.1.1.tar.gz", -) - -http_archive( - name = "absl_py", - sha256 = "8a3d0830e4eb4f66c4fa907c06edf6ce1c719ced811a12e26d9d3162f8471758", - strip_prefix = "abseil-py-2.1.0", - url = "https://github.com/abseil/abseil-py/archive/refs/tags/v2.1.0.tar.gz", -) - -http_archive( - name = "nlohmann_json", - sha256 = "34660b5e9a407195d55e8da705ed26cc6d175ce5a6b1fb957e701fb4d5b04022", - strip_prefix = "json-3.12.0", - url = "https://github.com/nlohmann/json/archive/refs/tags/v3.12.0.zip", -) - -http_archive( - name = "miniaudio", - build_file = "@//third_party/miniaudio:miniaudio.BUILD", - sha256 = "bcb07bfb27e6fa94d34da73ba2d5642d4940b208ec2a660dbf4e52e6b7cd492f", - strip_prefix = "miniaudio-0.11.22", - url = "https://github.com/mackron/miniaudio/archive/refs/tags/0.11.22.tar.gz", -) - -http_archive( - name = "stb", - build_file = "@//third_party/stb:stb.BUILD", - sha256 = "119b9f3cca3e50225dc946ed1acd1b7a160943bc8bf549760109cea4e4e7c836", - strip_prefix = "stb-f58f558c120e9b32c217290b80bad1a0729fbb2c", - url = "https://github.com/nothings/stb/archive/f58f558c120e9b32c217290b80bad1a0729fbb2c.zip", -) - -http_archive( - name = "skia", - patch_args = ["-p1"], - patch_cmds = [ - # Replace with "jpeglib.h". - "sed -i -e 's|#include |#include \"jpeglib.h\"|g' */*.cpp */*.h */*/*.cpp */*/*.h", - ], - patches = ["@//third_party/skia:skia.patch"], - repo_mapping = { - "@libpng": "@png", - }, - sha256 = "2fe28173428f8eebf2aa8a665bad32136086cc065f50c7154678a96250d1cde1", - strip_prefix = "skia-226ae9d866748a2e68b6dbf114b37129c380a298", - urls = ["https://github.com/google/skia/archive/226ae9d866748a2e68b6dbf114b37129c380a298.zip"], -) - -http_archive( - name = "skia_user_config", - patch_args = ["-p1"], - patches = ["@//third_party/skia:skia_user_config.patch"], - sha256 = "2fe28173428f8eebf2aa8a665bad32136086cc065f50c7154678a96250d1cde1", - strip_prefix = "skia-226ae9d866748a2e68b6dbf114b37129c380a298/include/config", - urls = ["https://github.com/google/skia/archive/226ae9d866748a2e68b6dbf114b37129c380a298.zip"], -) - -http_archive( - name = "espeak_ng", - build_file = "@//third_party/espeak_ng:espeak_ng.BUILD", - sha256 = "bb4338102ff3b49a81423da8a1a158b420124b055b60fa76cfb4b18677130a23", - strip_prefix = "espeak-ng-1.52.0", - urls = ["https://github.com/espeak-ng/espeak-ng/archive/refs/tags/1.52.0.tar.gz"], -) - -http_archive( - name = "cppjieba", - build_file = "@//third_party/cppjieba:cppjieba.BUILD", - patches = ["@//third_party/cppjieba:cppjieba.patch"], - sha256 = "8b27931630abab1136b7c3ee920e4a95e78cb84a3cab4670198172bc82104844", - strip_prefix = "OpenCC-025f371dc76b598d77384fbdab90c937471844d8/plugins/jieba/deps/cppjieba", - urls = ["https://github.com/BYVoid/OpenCC/archive/025f371dc76b598d77384fbdab90c937471844d8.tar.gz"], -) - -# Android rules #################################################################################### - -# Android SDK -load("@rules_android//:prereqs.bzl", "rules_android_prereqs") - -rules_android_prereqs() - -load("@rules_android//:defs.bzl", "rules_android_workspace") - -rules_android_workspace() - -load("@rules_java//java:repositories.bzl", "java_tools_repos") - -java_tools_repos() - -load("@rules_android//rules:rules.bzl", "android_sdk_repository") - -android_sdk_repository(name = "androidsdk") - -register_toolchains( - "@rules_android//toolchains/android:android_default_toolchain", - "@rules_android//toolchains/android_sdk:android_sdk_tools", -) - -# Android NDK. Need latest rules_android_ndk to use NDK 26+. -load("@rules_android_ndk//:rules.bzl", "android_ndk_repository") - -android_ndk_repository(name = "androidndk") - -# Configure Android NDK only when ANDROID_NDK_HOME is set. -# Creates current_android_ndk_env.bzl as a workaround since shell environment is available only -# through repository rule's context. -load("//:android_ndk_env.bzl", "check_android_ndk_env") - -check_android_ndk_env(name = "android_ndk_env") - -load("@android_ndk_env//:current_android_ndk_env.bzl", "ANDROID_NDK_HOME_IS_SET") - -# Use "@android_ndk_env//:all" as a dummy toolchain target as register_toolchains() does not take -# an empty string. -register_toolchains("@androidndk//:all" if ANDROID_NDK_HOME_IS_SET else "@android_ndk_env//:all") - -# VENDOR SDKS ###################################################################################### - -# QUALCOMM --------------------------------------------------------------------------------------- - -# The actual macro call will be set during configure for now. -load("@litert//third_party/qairt:workspace.bzl", "qairt") - -qairt() - -# MEDIATEK --------------------------------------------------------------------------------------- - -# Currently only works with local sdk -load("@litert//third_party/neuro_pilot:workspace.bzl", "neuro_pilot") - -neuro_pilot() - -# GOOGLE TENSOR ---------------------------------------------------------------------------------- -load("@litert//third_party/google_tensor:workspace.bzl", "google_tensor") - -google_tensor() - -# INTEL OPENVINO --------------------------------------------------------------------------------- -load("@litert//third_party/intel_openvino:openvino.bzl", "openvino_configure") - -openvino_configure() - -# SAMSUNG EXYNOS_AI_LITECORE---------------------------------------------------------------------- -load("@litert//third_party/exynos_ai_litecore:workspace.bzl", "exynos_ai_litecore") - -exynos_ai_litecore() - -load("@rules_python//python:pip.bzl", "pip_parse") - -pip_parse( - name = "custom_pip_deps", - extra_pip_args = ["--index-url=https://pypi.org/simple"], - requirements_lock = "//:requirements.txt", -) - -load("@custom_pip_deps//:requirements.bzl", install_custom_deps = "install_deps") - -install_custom_deps() - -# DirectX Shader Compiler DLLs for Windows -http_archive( - name = "directx_shader_compiler", - build_file = "@//third_party/directx_shader_compiler:directx_shader_compiler.BUILD", - sha256 = "a1e89031421cf3c1fca6627766ab3020ca4f962ac7e2caa7fab2b33a8436151e", - url = "https://github.com/microsoft/DirectXShaderCompiler/releases/download/v1.9.2602/dxc_2026_02_20.zip", -) - -http_archive( - name = "patchelf_linux_x86_64", - build_file_content = """ -filegroup( - name = "patchelf", - srcs = ["bin/patchelf"], - visibility = ["//visibility:public"], -) -""", - sha256 = "ce84f2447fb7a8679e58bc54a20dc2b01b37b5802e12c57eece772a6f14bf3f0", - url = "https://github.com/NixOS/patchelf/releases/download/0.18.0/patchelf-0.18.0-x86_64.tar.gz", -) - -http_archive( - name = "patchelf_linux_arm64", - build_file_content = """ -filegroup( - name = "patchelf", - srcs = ["bin/patchelf"], - visibility = ["//visibility:public"], -) -""", - sha256 = "ae13e2effe077e829be759182396b931d8f85cfb9cfe9d49385516ea367ef7b2", - url = "https://github.com/NixOS/patchelf/releases/download/0.18.0/patchelf-0.18.0-aarch64.tar.gz", -) diff --git a/tools/fixtures/omni_asr_BUILD_v018.txt b/tools/fixtures/omni_asr_BUILD_v018.txt deleted file mode 100644 index 2807a54..0000000 --- a/tools/fixtures/omni_asr_BUILD_v018.txt +++ /dev/null @@ -1,700 +0,0 @@ -# Copyright 2026 The ODML Authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [Google-internal load of `cc_binary`] -# [Google-internal load of `cc_library`] -# [Google-internal load of `cc_test`] - -package(default_visibility = ["//visibility:public"]) - -cc_library( - name = "audio_source", - hdrs = ["audio_source.h"], - deps = [ - "@com_google_absl//absl/status", - "//omni/base:stage", - ], -) - -cc_library( - name = "file_audio_source", - srcs = ["file_audio_source.cc"], - hdrs = ["file_audio_source.h"], - deps = [ - ":audio_source", - "@com_google_absl//absl/base:core_headers", - "@com_google_absl//absl/cleanup", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_macros", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/strings", - "@com_google_absl//absl/strings:string_view", - "@com_google_absl//absl/time", - ] + select({ - "@platforms//os:ios": ["@miniaudio//:miniaudio_objc"], - "@platforms//os:macos": ["@miniaudio//:miniaudio_objc"], - "//conditions:default": ["@miniaudio"], - }), -) - -cc_test( - name = "file_audio_source_test", - srcs = ["file_audio_source_test.cc"], - deps = [ - ":file_audio_source", - "@com_google_googletest//:gtest_main", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_matchers", - "@com_google_absl//absl/strings", - "@com_google_absl//absl/time", - "//support/util:test_utils", - ] + select({ - "@platforms//os:ios": ["@miniaudio//:miniaudio_objc"], - "@platforms//os:macos": ["@miniaudio//:miniaudio_objc"], - "//conditions:default": ["@miniaudio"], - }), -) - -cc_library( - name = "audio_preprocessor", - hdrs = ["audio_preprocessor.h"], - deps = [ - "@com_google_absl//absl/base:nullability", - "//omni/base:stage", - ], -) - -cc_library( - name = "log_mel_spectrogram_processor", - srcs = ["log_mel_spectrogram_processor.cc"], - hdrs = ["log_mel_spectrogram_processor.h"], - deps = [ - ":audio_preprocessor", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/cleanup", - "@com_google_absl//absl/memory", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_macros", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/strings:string_view", - "@com_google_absl//absl/types:span", - "@litert//litert/cc:litert_macros", - "@litert//litert/cc:litert_tensor_buffer", - "//omni/base:stage", - "//support/preprocessor:audio_preprocessor", - "//support/preprocessor:audio_preprocessor_miniaudio", - "//support/util:io_types", - ], -) - -cc_library( - name = "dummy_preprocessor", - hdrs = ["dummy_preprocessor.h"], - deps = [ - ":audio_preprocessor", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/cleanup", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_macros", - "//omni/base:stage", - ], -) - -cc_test( - name = "log_mel_spectrogram_processor_test", - srcs = ["log_mel_spectrogram_processor_test.cc"], - deps = [ - ":log_mel_spectrogram_processor", - "@com_google_googletest//:gtest_main", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_matchers", - "//omni/base:stage", - "//support/util:test_utils", - ], -) - -cc_library( - name = "speech_recognizer", - hdrs = ["speech_recognizer.h"], - deps = [ - "@com_google_absl//absl/base:nullability", - "//omni/base:stage", - ], -) - -cc_library( - name = "ctc_decoder", - srcs = ["ctc_decoder.cc"], - hdrs = ["ctc_decoder.h"], - deps = [ - ":litert_speech_recognizer", - ":speech_recognizer", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/types:span", - "@litert//litert/cc:litert_macros", - "@litert//litert/cc:litert_tensor_buffer", - ], -) - -cc_test( - name = "ctc_decoder_test", - srcs = ["ctc_decoder_test.cc"], - deps = [ - ":ctc_decoder", - "@com_google_googletest//:gtest_main", - "@com_google_absl//absl/status:status_matchers", - "@litert//litert/cc:litert_element_type", - "@litert//litert/cc:litert_layout", - "@litert//litert/cc:litert_ranked_tensor_type", - "@litert//litert/cc:litert_tensor_buffer", - "//support/util:test_utils", - ], -) - -cc_library( - name = "stateless_decoder", - srcs = ["stateless_decoder.cc"], - hdrs = ["stateless_decoder.h"], - deps = [ - ":litert_speech_recognizer", - ":speech_recognizer", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/strings", - "@com_google_absl//absl/types:span", - "@litert//litert/cc:litert_macros", - "@litert//litert/cc:litert_tensor_buffer", - "//omni/base:litert_runner", - ], -) - -cc_test( - name = "stateless_decoder_test", - srcs = ["stateless_decoder_test.cc"], - deps = [ - ":stateless_decoder", - "@com_google_googletest//:gtest_main", - "@com_google_absl//absl/status", - "@com_google_absl//absl/strings", - "@com_google_absl//absl/types:span", - "@litert//litert/cc:litert_element_type", - "@litert//litert/cc:litert_layout", - "@litert//litert/cc:litert_ranked_tensor_type", - "@litert//litert/cc:litert_tensor_buffer", - "//omni/base:mock_litert_runner", - "//support/util:test_utils", - ], -) - -cc_library( - name = "tdt_decoder", - srcs = ["tdt_decoder.cc"], - hdrs = ["tdt_decoder.h"], - deps = [ - ":litert_speech_recognizer", - ":speech_recognizer", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/container:flat_hash_map", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_macros", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/strings", - "@com_google_absl//absl/types:span", - "@litert//litert/cc:litert_macros", - "@litert//litert/cc:litert_tensor_buffer", - "//omni/base:litert_runner", - "//omni/base:stateful_litert_runner", - ], -) - -cc_test( - name = "tdt_decoder_test", - srcs = ["tdt_decoder_test.cc"], - deps = [ - ":tdt_decoder", - "@com_google_googletest//:gtest_main", - "@com_google_absl//absl/status", - "@com_google_absl//absl/strings", - "@com_google_absl//absl/types:span", - "@litert//litert/cc:litert_element_type", - "@litert//litert/cc:litert_layout", - "@litert//litert/cc:litert_ranked_tensor_type", - "@litert//litert/cc:litert_tensor_buffer", - "//omni/base:mock_litert_runner", - "//support/util:test_utils", - ], -) - -cc_library( - name = "lm_decoder", - srcs = ["lm_decoder.cc"], - hdrs = ["lm_decoder.h"], - deps = [ - ":litert_speech_recognizer", - ":speech_recognizer", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/container:flat_hash_set", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_macros", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/types:span", - "@litert//litert/cc:litert_macros", - "@litert//litert/cc:litert_tensor_buffer", - "@litert//litert/cc:litert_tensor_buffer_types", - "//omni/base:litert_lm_runner", - "//omni/base:model_utils", - "//runtime/proto:token_cc_proto", - "//runtime/util:tensor_buffer_util", - "//support/tokenizer", - "//support/util:convert_tensor_buffer", - ], -) - -cc_test( - name = "lm_decoder_test", - srcs = ["lm_decoder_test.cc"], - deps = [ - ":lm_decoder", - ":speech_recognizer", - "@com_google_googletest//:gtest_main", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_matchers", - "@com_google_absl//absl/types:span", - "@litert//litert/cc:litert_element_type", - "@litert//litert/cc:litert_layout", - "@litert//litert/cc:litert_ranked_tensor_type", - "@litert//litert/cc:litert_tensor_buffer", - "//omni/base:mock_litert_lm_runner", - "//support/util:test_utils", - ], -) - -cc_library( - name = "lm_engine_decoder", - srcs = ["lm_engine_decoder.cc"], - hdrs = ["lm_engine_decoder.h"], - deps = [ - ":litert_speech_recognizer", - ":speech_recognizer", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/container:flat_hash_set", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_macros", - "@com_google_absl//absl/status:statusor", - "@litert//litert/cc:litert_macros", - "@litert//litert/cc:litert_tensor_buffer", - "//omni/base:litert_lm_engine_runner", - "//runtime/components:model_resources", - "//runtime/engine:io_types", - "//runtime/proto:token_cc_proto", - "//support/tokenizer", - "//support/util:convert_tensor_buffer", - ], -) - -cc_test( - name = "lm_engine_decoder_test", - srcs = ["lm_engine_decoder_test.cc"], - deps = [ - ":lm_engine_decoder", - "@com_google_googletest//:gtest_main", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_matchers", - "@litert//litert/cc:litert_tensor_buffer", - "//omni/base:litert_lm_engine_runner", - "//runtime/components:model_resources", - "//runtime/engine:io_types", - "//support/util:convert_tensor_buffer", - ], -) - -cc_library( - name = "litert_speech_recognizer", - srcs = ["litert_speech_recognizer.cc"], - hdrs = ["litert_speech_recognizer.h"], - deps = [ - ":speech_recognizer", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/cleanup", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_macros", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/strings", - "@com_google_absl//absl/types:span", - "@litert//litert/cc:litert_macros", - "@litert//litert/cc:litert_tensor_buffer", - "//omni/base:litert_runner", - "//omni/base:stage", - ], -) - -cc_test( - name = "litert_speech_recognizer_test", - srcs = ["litert_speech_recognizer_test.cc"], - deps = [ - ":litert_speech_recognizer", - ":speech_recognizer", - "@com_google_googletest//:gtest_main", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/strings", - "@litert//litert/cc:litert_element_type", - "@litert//litert/cc:litert_layout", - "@litert//litert/cc:litert_ranked_tensor_type", - "@litert//litert/cc:litert_tensor_buffer", - "//omni/base:mock_litert_runner", - "//omni/base:stage", - "//support/util:test_utils", - ], -) - -cc_library( - name = "detokenizer", - hdrs = ["detokenizer.h"], - deps = [ - ":speech_recognizer", - "@com_google_absl//absl/base:nullability", - "//omni/base:stage", - ], -) - -cc_library( - name = "tokenizer_detokenizer", - srcs = ["tokenizer_detokenizer.cc"], - hdrs = ["tokenizer_detokenizer.h"], - deps = [ - ":detokenizer", - ":speech_recognizer", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/cleanup", - "@com_google_absl//absl/log:absl_log", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_macros", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/strings", - "//omni/base:stage", - "//support/tokenizer", - ], -) - -cc_test( - name = "tokenizer_detokenizer_test", - srcs = ["tokenizer_detokenizer_test.cc"], - deps = [ - ":speech_recognizer", - ":tokenizer_detokenizer", - "@com_google_googletest//:gtest_main", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_matchers", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/strings:string_view", - "@com_google_absl//absl/types:span", - "//omni/base:stage", - "//support/tokenizer", - "//support/util:test_utils", - ], -) - -cc_library( - name = "text_merger", - hdrs = ["text_merger.h"], - deps = [ - ":detokenizer", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/status", - "//omni/base:stage", - ], -) - -cc_library( - name = "levenshtein_align", - srcs = ["levenshtein_align.cc"], - hdrs = ["levenshtein_align.h"], - deps = [ - "@com_google_absl//absl/strings", - "@com_google_absl//absl/types:span", - ], -) - -cc_test( - name = "levenshtein_align_test", - srcs = ["levenshtein_align_test.cc"], - deps = [ - ":levenshtein_align", - "@com_google_googletest//:gtest_main", - ], -) - -cc_library( - name = "levenshtein_text_merger", - srcs = ["levenshtein_text_merger.cc"], - hdrs = ["levenshtein_text_merger.h"], - deps = [ - ":detokenizer", - ":levenshtein_align", - ":text_merger", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_macros", - "@com_google_absl//absl/strings", - "@com_google_absl//absl/synchronization", - "@com_google_absl//absl/types:span", - "//omni/base:stage", - ], -) - -cc_test( - name = "levenshtein_text_merger_test", - srcs = ["levenshtein_text_merger_test.cc"], - deps = [ - ":detokenizer", - ":levenshtein_text_merger", - ":text_merger", - "@com_google_googletest//:gtest_main", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:statusor", - "@litert//litert/cc:litert_macros", - "//omni/base:stage", - ], -) - -cc_library( - name = "timestamp_text_merger", - srcs = ["timestamp_text_merger.cc"], - hdrs = ["timestamp_text_merger.h"], - deps = [ - ":detokenizer", - ":levenshtein_align", - ":text_merger", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/log:absl_log", - "@com_google_absl//absl/status", - "@com_google_absl//absl/strings", - "@com_google_absl//absl/synchronization", - "@com_google_absl//absl/types:span", - "@litert//litert/cc:litert_macros", - "//omni/base:stage", - ], -) - -cc_test( - name = "timestamp_text_merger_test", - srcs = ["timestamp_text_merger_test.cc"], - deps = [ - ":detokenizer", - ":text_merger", - ":timestamp_text_merger", - "@com_google_googletest//:gtest_main", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_matchers", - "@com_google_absl//absl/status:statusor", - "@litert//litert/cc:litert_macros", - "//omni/base:stage", - "//support/util:test_utils", - ], -) - -cc_library( - name = "asr_session", - srcs = ["asr_session.cc"], - hdrs = ["asr_session.h"], - deps = [ - ":audio_preprocessor", - ":audio_source", - ":detokenizer", - ":speech_recognizer", - ":text_merger", - "@com_google_absl//absl/base:core_headers", - "@com_google_absl//absl/functional:any_invocable", - "@com_google_absl//absl/log:absl_check", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_macros", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/synchronization", - "@com_google_absl//absl/time", - "//omni:omni_session", - "//omni/base:async_stage_scheduler", - "//omni/base:stage", - "//runtime/framework:threadpool", - ], -) - -cc_test( - name = "asr_session_test", - srcs = ["asr_session_test.cc"], - deps = [ - ":asr_session", - ":audio_preprocessor", - ":audio_source", - ":detokenizer", - ":levenshtein_text_merger", - ":speech_recognizer", - ":text_merger", - "@com_google_googletest//:gtest_main", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/cleanup", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_matchers", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/synchronization", - "@com_google_absl//absl/time", - "//omni:omni_session", - "//omni/base:stage", - "//runtime/framework:threadpool", - "//support/util:test_utils", - ], -) - -cc_library( - name = "asr_engine", - srcs = ["asr_engine.cc"], - hdrs = ["asr_engine.h"], - data = ["model_metadata.json"], - deps = [ - ":asr_session", - ":audio_preprocessor", - ":audio_source", - ":ctc_decoder", - ":dummy_preprocessor", - ":levenshtein_text_merger", - ":litert_speech_recognizer", - ":lm_decoder", - ":lm_engine_decoder", - ":log_mel_spectrogram_processor", - ":stateless_decoder", - ":tdt_decoder", - ":text_merger", - ":timestamp_text_merger", - ":tokenizer_detokenizer", - "@com_google_absl//absl/functional:any_invocable", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_macros", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/strings", - "@litert//litert/cc:litert_buffer_ref", - "@litert//litert/cc:litert_common", - "@litert//litert/cc:litert_compiled_model", - "@litert//litert/cc:litert_environment", - "@litert//litert/cc:litert_macros", - "@litert//litert/cc:litert_options", - "@litert//litert/cc/options:litert_cpu_options", - "@litert//litert/cc/options:litert_gpu_options", - "@litert//litert/cc/options:litert_qualcomm_options", - "//omni/base:litert_lm_engine_runner", - "//omni/base:litert_lm_runner", - "//omni/base:litert_runner", - "//omni/base:model_utils", - "//runtime/components:model_resources", - "//runtime/executor:executor_settings_base", - "//runtime/framework:threadpool", - "//support/tokenizer", - "//support/tokenizer:huggingface_tokenizer", - ], -) - -cc_library( - name = "asr_omni_session", - srcs = ["asr_omni_session.cc"], - hdrs = ["asr_omni_session.h"], - deps = [ - ":asr_engine", - ":audio_source", - "@com_google_absl//absl/base:nullability", - "@com_google_absl//absl/cleanup", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_macros", - "@com_google_absl//absl/status:statusor", - "//omni:omni_session", - ], -) - -cc_binary( - name = "asr_runner", - srcs = ["asr_runner.cc"], - deps = [ - ":asr_engine", - ":file_audio_source", - ":model_metadata", - "@com_google_absl//absl/flags:flag", - "@com_google_absl//absl/flags:parse", - "@com_google_absl//absl/log:absl_log", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:status_macros", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/strings", - "@com_google_absl//absl/strings:str_format", - "@com_google_absl//absl/time", - "//omni:omni_session", - "//runtime/executor:default_static_gpu_accelerator", - ], -) - -genrule( - name = "model_metadata_embedded_h", - srcs = ["model_metadata.json"], - outs = ["model_metadata_embedded.h"], - cmd = """ -cat << 'EOF' > $@ -#ifndef THIRD_PARTY_ODML_LITERT_LM_OMNI_ASR_MODEL_METADATA_EMBEDDED_H_ -#define THIRD_PARTY_ODML_LITERT_LM_OMNI_ASR_MODEL_METADATA_EMBEDDED_H_ - -namespace litert::omni::asr { - -inline constexpr char kEmbeddedModelMetadataJson[] = R"json( -EOF -cat $< >> $@ -cat << 'EOF' >> $@ -)json"; - -} // namespace litert::omni::asr - -#endif // THIRD_PARTY_ODML_LITERT_LM_OMNI_ASR_MODEL_METADATA_EMBEDDED_H_ -EOF -""", -) - -cc_library( - name = "model_metadata_embedded", - hdrs = ["model_metadata_embedded.h"], -) - -cc_library( - name = "model_metadata", - srcs = ["model_metadata.cc"], - hdrs = ["model_metadata.h"], - deps = [ - ":asr_engine", - ":log_mel_spectrogram_processor", - ":model_metadata_embedded", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:statusor", - "@com_google_absl//absl/strings", - "@com_google_absl//absl/strings:string_view", - "@nlohmann_json//:json", # TPMonster:discouraged-dependencies - ], -) - -cc_test( - name = "model_metadata_test", - srcs = ["model_metadata_test.cc"], - deps = [ - ":asr_engine", - ":model_metadata", - "@com_google_googletest//:gtest_main", - "@com_google_absl//absl/status", - "//support/util:test_utils", - ], -) diff --git a/tools/fixtures/timestamp_text_merger_v018.cc b/tools/fixtures/timestamp_text_merger_v018.cc deleted file mode 100644 index bfd3140..0000000 --- a/tools/fixtures/timestamp_text_merger_v018.cc +++ /dev/null @@ -1,325 +0,0 @@ -// Copyright 2026 The ODML Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "omni/asr/timestamp_text_merger.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "absl/base/nullability.h" // from @com_google_absl -#include "absl/log/absl_log.h" // from @com_google_absl -#include "absl/status/status.h" // from @com_google_absl -#include "absl/strings/str_join.h" // from @com_google_absl -#include "absl/strings/string_view.h" // from @com_google_absl -#include "absl/synchronization/mutex.h" // from @com_google_absl -#include "absl/types/span.h" // from @com_google_absl -#include "litert/cc/litert_macros.h" // from @litert -#include "omni/asr/detokenizer.h" -#include "omni/asr/levenshtein_align.h" -#include "omni/asr/text_merger.h" -#include "omni/base/stage.h" - -namespace litert::omni::asr { -namespace { - -std::vector MergeTimestamps(absl::Span prev_timestamps, - absl::Span curr_timestamps, - int prev_word_index_of_unconfirmed, - int prev_word_index_of_pivot, - size_t num_merged_words) { - if (num_merged_words == 0) { - return {}; - } - - if (prev_timestamps.empty() || prev_word_index_of_unconfirmed == -1 || - prev_word_index_of_unconfirmed >= - static_cast(prev_timestamps.size()) || - prev_word_index_of_unconfirmed == prev_word_index_of_pivot) { - return std::vector(curr_timestamps.begin(), curr_timestamps.end()); - } - - size_t num_words_from_prev = - prev_word_index_of_pivot - prev_word_index_of_unconfirmed; - if (num_words_from_prev > - prev_timestamps.size() - prev_word_index_of_unconfirmed) { - num_words_from_prev = - prev_timestamps.size() - prev_word_index_of_unconfirmed; - } - - std::vector result( - prev_timestamps.begin() + prev_word_index_of_unconfirmed, - prev_timestamps.begin() + prev_word_index_of_unconfirmed + - num_words_from_prev); - if (num_merged_words > num_words_from_prev) { - size_t num_words_from_curr = num_merged_words - num_words_from_prev; - if (num_words_from_curr <= curr_timestamps.size()) { - result.insert(result.end(), curr_timestamps.end() - num_words_from_curr, - curr_timestamps.end()); - } else { - result.insert(result.end(), curr_timestamps.begin(), - curr_timestamps.end()); - } - } - return result; -} - -std::vector MergeIntoUnconfirmedText( - absl::Span prev_words, - absl::Span prev_timestamps, - absl::Span curr_words, - absl::Span curr_timestamps, float overlap_ratio, - float pivot_factor, int prev_word_index_of_unconfirmed, - int prev_word_index_of_pivot) { - if (prev_word_index_of_unconfirmed == -1 || - prev_word_index_of_unconfirmed >= static_cast(prev_words.size())) { - return std::vector(curr_words.begin(), curr_words.end()); - } - - bool use_timestamps = !curr_timestamps.empty() && !prev_timestamps.empty() && - (prev_timestamps.back() > prev_timestamps.front() || - curr_timestamps.back() > curr_timestamps.front()); - size_t num_words_before_pivot_in_current = 0; - if (use_timestamps) { - int timestamp_at_pivot = - (prev_word_index_of_pivot >= static_cast(prev_timestamps.size())) - ? prev_timestamps.back() + 1 - : prev_timestamps[prev_word_index_of_pivot]; - for (int ts : curr_timestamps) { - if (ts < timestamp_at_pivot) { - num_words_before_pivot_in_current++; - } - } - } else { - int num_words_overlap_in_current = std::max( - std::ceil(curr_words.size() * overlap_ratio), - static_cast(prev_words.size()) - prev_word_index_of_unconfirmed); - num_words_before_pivot_in_current = std::min( - static_cast(num_words_overlap_in_current * pivot_factor), - curr_words.size()); - } - - size_t num_words_in_prev_unconfirmed = std::max( - 0, prev_word_index_of_pivot - prev_word_index_of_unconfirmed); - num_words_before_pivot_in_current = std::min( - num_words_before_pivot_in_current, num_words_in_prev_unconfirmed); - - size_t num_words_after_pivot_in_current = - curr_words.size() - num_words_before_pivot_in_current; - if (num_words_after_pivot_in_current < - prev_words.size() - prev_word_index_of_pivot) { - return std::vector( - prev_words.begin() + prev_word_index_of_unconfirmed, prev_words.end()); - } - - std::vector result; - for (int i = prev_word_index_of_unconfirmed; i < prev_word_index_of_pivot; - ++i) { - result.push_back(prev_words[i]); - } - std::vector curr_tail( - curr_words.begin() + num_words_before_pivot_in_current, curr_words.end()); - std::vector deduped_tail = - DedupWords(absl::MakeSpan(result), absl::MakeSpan(curr_tail)); - result.insert(result.end(), deduped_tail.begin(), deduped_tail.end()); - return result; -} - -} // namespace - -TimestampTextMerger::TimestampTextMerger( - Stage>* absl_nonnull detokenizer, - float overlap_ratio, int search_window, int max_levenshtein_distance, - float pivot_factor) - : TextMerger(detokenizer), - overlap_ratio_(overlap_ratio), - search_window_(search_window), - max_levenshtein_distance_(max_levenshtein_distance), - pivot_factor_(pivot_factor) {} - -void TimestampTextMerger::ResetInternal() { - prev_words_.clear(); - prev_timestamps_.clear(); - last_confirmed_words_.clear(); - prev_word_index_of_unconfirmed_ = -1; - prev_word_index_of_pivot_ = -1; - stream_timestamp_offset_ms_ = 0; -} - -absl::Status TimestampTextMerger::ScheduleInternal() { - SetState(State::kRunning); - auto status = Execute(); - SetState(State::kIdle); - return status; -} - -absl::Status TimestampTextMerger::Execute() { - LITERT_ASSIGN_OR_RETURN(auto curr_chunk_words, detokenizer_.GetOutput()); - if (curr_chunk_words.empty()) { - LogAndPushOutput( - {"", prev_words_.empty() ? "" : absl::StrJoin(prev_words_, " ")}); - return absl::OkStatus(); - } - - std::vector curr_words; - std::vector curr_timestamps; - std::optional max_chunk_timestamp_ms; - curr_words.reserve(curr_chunk_words.size()); - for (const auto& word : curr_chunk_words) { - if (word.IsEndOfChunk()) { - if (word.timestamp_ms.has_value()) { - max_chunk_timestamp_ms = word.timestamp_ms.value(); - } - continue; - } - curr_words.push_back(word.text); - if (word.timestamp_ms.has_value()) { - curr_timestamps.push_back(word.timestamp_ms.value() + - stream_timestamp_offset_ms_); - } - } - - if (overlap_ratio_ == 0.0f) { - LogAndPushOutput({absl::StrJoin(curr_words, " "), ""}); - return absl::OkStatus(); - } - - if (prev_words_.empty()) { - prev_words_ = curr_words; - prev_timestamps_ = curr_timestamps; - UpdateStreamTimestampOffset(max_chunk_timestamp_ms, curr_timestamps); - LogAndPushOutput({"", absl::StrJoin(prev_words_, " ")}); - return absl::OkStatus(); - } - - int middle_index_to_search = 0; - if (!prev_timestamps_.empty() && !curr_timestamps.empty() && - (prev_timestamps_.back() > prev_timestamps_.front() || - curr_timestamps.back() > curr_timestamps.front())) { - int target_timestamp = curr_timestamps.front(); - int found_idx = -1; - for (size_t i = 0; i < prev_timestamps_.size(); ++i) { - if (prev_timestamps_[i] >= target_timestamp) { - found_idx = static_cast(i); - break; - } - } - middle_index_to_search = - (found_idx != -1) - ? found_idx - : static_cast(prev_words_.size() * (1 - overlap_ratio_)); - } else { - middle_index_to_search = - static_cast(prev_words_.size() * (1 - overlap_ratio_)); - } - - int min_distance = max_levenshtein_distance_; - prev_word_index_of_unconfirmed_ = std::min( - middle_index_to_search + search_window_ + 1, prev_words_.size()); - - for (int i = -search_window_; i <= search_window_; ++i) { - int start_index = - std::clamp(middle_index_to_search + i, 0, prev_words_.size()); - int end_index = - std::min(start_index + curr_words.size(), prev_words_.size()); - if (start_index >= end_index) continue; - - auto prev_sub = absl::MakeSpan(prev_words_) - .subspan(start_index, end_index - start_index); - auto curr_sub = absl::MakeSpan(curr_words) - .subspan(0, std::min(end_index - start_index, - curr_words.size())); - - int dist = ComputeLevenshteinDistanceWords(CanonicalizeWords(prev_sub), - CanonicalizeWords(curr_sub)); - if (dist < min_distance) { - min_distance = dist; - prev_word_index_of_unconfirmed_ = start_index; - } - } - - int unconfirmed_until_pivot = std::ceil( - (prev_words_.size() - prev_word_index_of_unconfirmed_) * pivot_factor_); - prev_word_index_of_pivot_ = - std::min(prev_word_index_of_unconfirmed_ + unconfirmed_until_pivot, - prev_words_.size()); - - last_confirmed_words_ = std::vector( - prev_words_.begin(), - prev_words_.begin() + prev_word_index_of_unconfirmed_); - - std::vector unconfirmed_merged = MergeIntoUnconfirmedText( - prev_words_, prev_timestamps_, curr_words, curr_timestamps, - overlap_ratio_, pivot_factor_, prev_word_index_of_unconfirmed_, - prev_word_index_of_pivot_); - - prev_timestamps_ = MergeTimestamps( - prev_timestamps_, curr_timestamps, prev_word_index_of_unconfirmed_, - prev_word_index_of_pivot_, unconfirmed_merged.size()); - prev_words_ = unconfirmed_merged; - UpdateStreamTimestampOffset(max_chunk_timestamp_ms, curr_timestamps); - - LogAndPushOutput({absl::StrJoin(last_confirmed_words_, " "), - absl::StrJoin(prev_words_, " ")}); - return absl::OkStatus(); -} - -absl::Status TimestampTextMerger::Flush() { - if (!SetStateIfState(State::kIdle, State::kRunning)) { - return absl::FailedPreconditionError( - "Flush() called while Schedule() is in progress."); - } - - if (!prev_words_.empty()) { - MergeResult result = {absl::StrJoin(prev_words_, " "), ""}; - prev_words_.clear(); - prev_timestamps_.clear(); - last_confirmed_words_.clear(); - prev_word_index_of_unconfirmed_ = -1; - prev_word_index_of_pivot_ = -1; - LogAndPushOutput(std::move(result)); - } - - SetState(State::kIdle); - return absl::OkStatus(); -} - -void TimestampTextMerger::UpdateStreamTimestampOffset( - std::optional max_chunk_timestamp_ms, - absl::Span curr_timestamps) { - if (overlap_ratio_ <= 0.0f) return; - - int max_ts = - max_chunk_timestamp_ms.has_value() - ? max_chunk_timestamp_ms.value() - : (curr_timestamps.empty() - ? 0 - : curr_timestamps.back() - stream_timestamp_offset_ms_); - int timestamp_step = static_cast(max_ts * (1.0f - overlap_ratio_)); - if (timestamp_step > 0) { - stream_timestamp_offset_ms_ += timestamp_step; - } -} - -void TimestampTextMerger::LogAndPushOutput(MergeResult output) { - ABSL_VLOG(1) << "Merged text: confirmed=" << output.confirmed_text; - ABSL_VLOG(1) << "Merged text: unconfirmed=" << output.unconfirmed_text; - PushOutput(std::move(output)); -} - -} // namespace litert::omni::asr diff --git a/tools/fixtures/timestamp_text_merger_v020.cc b/tools/fixtures/timestamp_text_merger_v020.cc new file mode 100644 index 0000000..751bb23 --- /dev/null +++ b/tools/fixtures/timestamp_text_merger_v020.cc @@ -0,0 +1,877 @@ +// Copyright 2026 The ODML Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "omni/speech2text/timestamp_text_merger.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" // from @com_google_absl +#include "absl/base/no_destructor.h" // from @com_google_absl +#include "absl/base/nullability.h" // from @com_google_absl +#include "absl/container/flat_hash_map.h" // from @com_google_absl +#include "absl/log/absl_log.h" // from @com_google_absl +#include "absl/log/absl_vlog_is_on.h" // from @com_google_absl +#include "absl/status/status.h" // from @com_google_absl +#include "absl/strings/match.h" // from @com_google_absl +#include "absl/strings/str_cat.h" // from @com_google_absl +#include "absl/strings/string_view.h" // from @com_google_absl +#include "absl/types/span.h" // from @com_google_absl +#include "litert/cc/litert_macros.h" // from @litert +#include "omni/base/stage.h" +#include "omni/speech2text/detokenizer.h" +#include "omni/speech2text/levenshtein_align.h" +#include "omni/speech2text/text_merger.h" +#include "omni/utils/text_utils.h" + +namespace litert::omni::asr { +namespace { + +// Alignment costs. A substitution (same acoustic event, different words) is +// cheaper than an insertion plus a deletion but costlier than a match plus an +// indel, so a matching word is never traded for two substitutions. Pairing +// words whose timestamps disagree costs more than an indel pair, so it never +// happens. +constexpr int kMatchCost = 0; +constexpr int kIndelCost = 2; +constexpr int kSubstitutionCost = 3; +constexpr int kFarPairCost = 5; + +enum class AlignOp { kPair, kPrevOnly, kCurrOnly }; + +// Timestamp tolerances of a merge, in timestamp units, scaled from the length +// of the overlap. Emission times of the same word differ between the two +// windows: near the end of its window the previous chunk tends to emit early +// (up to ~40% of the overlap has been observed), the current chunk rarely +// emits earlier than the previous one did. +struct Tolerances { + // Max |dt| for two different words to be the same acoustic event. + double substitution; + // Max (prev - curr) for close-enough words to be the same word. + double match_early; + // Max (curr - prev) for close-enough words to be the same word. + double match_late; +}; + +bool HasUsableTimestamps(absl::Span words, + absl::Span timestamps) { + return !words.empty() && timestamps.size() == words.size() && + absl::c_is_sorted(timestamps); +} + +bool HasDistinctTimestamps(absl::Span timestamps) { + return !timestamps.empty() && timestamps.back() > timestamps.front(); +} + +std::vector> BuildCloseEnoughMatrix( + absl::Span canon_prev, + absl::Span canon_curr) { + std::vector> matrix( + canon_prev.size(), std::vector(canon_curr.size(), false)); + for (size_t i = 0; i < canon_prev.size(); ++i) { + for (size_t j = 0; j < canon_curr.size(); ++j) { + matrix[i][j] = CloseEnoughCanonical(canon_prev[i], canon_curr[j]); + } + } + return matrix; +} + +// Returns the shift that best maps the current chunk's timestamps onto the +// previous chunk's: the most frequent `curr - prev` difference among pairs of +// close-enough words (>= 2 canonical chars) in the overlap region within +// `max_shift`, with ties broken towards 0. At least two supporting pairs are +// required, otherwise 0 is returned. This absorbs a systematic emission delay +// between the two windows. +int EstimateTimestampShift(absl::Span canon_prev, + absl::Span prev_timestamps, + absl::Span canon_curr, + absl::Span curr_timestamps, + double stream_offset_ms, double prev_end_ms, + double max_shift) { + std::map support; + const double min_prev_ts = stream_offset_ms - 2.0 * max_shift; + const double max_curr_ts = prev_end_ms + 2.0 * max_shift; + for (size_t i = 0; i < canon_prev.size(); ++i) { + if (canon_prev[i].size() < 2 || prev_timestamps[i] < min_prev_ts) continue; + for (size_t j = 0; j < canon_curr.size(); ++j) { + if (canon_curr[j].size() < 2 || curr_timestamps[j] > max_curr_ts) { + continue; + } + const int shift = curr_timestamps[j] - prev_timestamps[i]; + if (std::abs(shift) > max_shift) continue; + if (CloseEnoughCanonical(canon_prev[i], canon_curr[j])) ++support[shift]; + } + } + int best_shift = 0; + int best_support = 1; + for (const auto& [shift, count] : support) { + if (count > best_support || + (count == best_support && std::abs(shift) < std::abs(best_shift))) { + best_shift = shift; + best_support = count; + } + } + return best_shift; +} + +int PairCost(bool is_close_enough, double prev_time, double curr_time, + const Tolerances& tol) { + const double dt = curr_time - prev_time; + if (is_close_enough) { + return (dt >= -tol.match_early && dt <= tol.match_late) ? kMatchCost + : kFarPairCost; + } + return std::fabs(dt) <= tol.substitution ? kSubstitutionCost : kFarPairCost; +} + +// Monotone alignment of the overlapping words of the two chunks: a Levenshtein +// alignment in which words may only be paired when their timestamps agree +// (see `Tolerances`). Words that are far apart in time are never paired. +std::vector AlignOverlap( + const std::vector>& close_matrix, + absl::Span prev_timestamps, absl::Span curr_times, + const Tolerances& tol) { + const size_t num_prev = prev_timestamps.size(); + const size_t num_curr = curr_times.size(); + + std::vector> cost(num_prev + 1, + std::vector(num_curr + 1, 0)); + for (size_t i = 0; i <= num_prev; ++i) cost[i][0] = i * kIndelCost; + for (size_t j = 0; j <= num_curr; ++j) cost[0][j] = j * kIndelCost; + for (size_t i = 1; i <= num_prev; ++i) { + for (size_t j = 1; j <= num_curr; ++j) { + const int pair_cost = + PairCost(close_matrix[i - 1][j - 1], prev_timestamps[i - 1], + curr_times[j - 1], tol); + cost[i][j] = + std::min({cost[i - 1][j - 1] + pair_cost, cost[i - 1][j] + kIndelCost, + cost[i][j - 1] + kIndelCost}); + } + } + + std::vector ops; + ops.reserve(num_prev + num_curr); + size_t i = num_prev; + size_t j = num_curr; + while (i > 0 || j > 0) { + if (i > 0 && j > 0) { + const int pair_cost = + PairCost(close_matrix[i - 1][j - 1], prev_timestamps[i - 1], + curr_times[j - 1], tol); + if (cost[i][j] == cost[i - 1][j - 1] + pair_cost) { + ops.push_back(AlignOp::kPair); + --i; + --j; + continue; + } + } + const bool prev_only_ok = + i > 0 && cost[i][j] == cost[i - 1][j] + kIndelCost; + const bool curr_only_ok = + j > 0 && cost[i][j] == cost[i][j - 1] + kIndelCost; + // When both are optimal, emit (walking backwards) the later word first so + // that unmatched words of the two chunks interleave in time order. + if (prev_only_ok && + (!curr_only_ok || prev_timestamps[i - 1] >= curr_times[j - 1])) { + ops.push_back(AlignOp::kPrevOnly); + --i; + } else { + ops.push_back(AlignOp::kCurrOnly); + --j; + } + } + std::reverse(ops.begin(), ops.end()); + return ops; +} + +bool HasWordWithin(absl::Span times, double time, + double tolerance) { + for (double t : times) { + if (std::fabs(t - time) <= tolerance) return true; + } + return false; +} + +// Marks which words in `prev_ov_words` were paired with a close-enough word in +// `curr_words` by `ops`. +std::vector FindMatchedPrevOverlapWords( + const std::vector>& close_matrix, + absl::Span ops) { + std::vector prev_ov_matched(close_matrix.size(), false); + size_t pi = 0; + size_t cj = 0; + for (AlignOp op : ops) { + if (op == AlignOp::kPair) { + if (close_matrix[pi][cj]) { + prev_ov_matched[pi] = true; + } + ++pi; + ++cj; + } else if (op == AlignOp::kPrevOnly) { + ++pi; + } else { + ++cj; + } + } + return prev_ov_matched; +} + +// A current-only word before the pivot is kept only where the previous chunk +// heard nothing: it is dropped when the previous chunk has an unpaired or +// substituted overlap word at about the same time. Words in `prev` that are +// already matched to their counterpart in `curr` only cover their own frame +// (`<= 1.0`), so short function words between matched words are not dropped. +bool IsCoveredByPrev(absl::Span prev_ov_ts, + const std::vector& prev_ov_matched, double time, + const Tolerances& tol) { + for (size_t idx = 0; idx < prev_ov_ts.size(); ++idx) { + const double limit = prev_ov_matched[idx] ? 1.0 : tol.substitution; + if (std::fabs(prev_ov_ts[idx] - time) <= limit) return true; + } + return false; +} + +// Returns true if `canon_curr` matches the spoken number or phonetic suffix of +// a numeric `canon_prev` token (e.g. "five" after "105" or "twenty" after +// "20"). +bool MatchesSpokenNumberSuffix(absl::string_view canon_prev, + absl::string_view canon_curr) { + if (canon_prev.empty() || canon_prev.back() < '0' || + canon_prev.back() > '9') { + return false; + } + + static const absl::NoDestructor< + absl::flat_hash_map>> + kSpokenNumberMap([] { + constexpr absl::string_view kOnes[] = {"zero", "one", "two", "three", + "four", "five", "six", "seven", + "eight", "nine"}; + constexpr absl::string_view kTeens[] = { + "ten", "eleven", "twelve", "thirteen", "fourteen", + "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; + constexpr absl::string_view kTens[] = { + "", "", "twenty", "thirty", "forty", + "fifty", "sixty", "seventy", "eighty", "ninety"}; + + absl::flat_hash_map> map = { + {"0", {"zero", "oh"}}, + {"00", {"hundred"}}, + {"000", {"thousand"}}, + }; + for (int d = 1; d <= 9; ++d) { + map[absl::StrCat(d)] = {std::string(kOnes[d])}; + map[absl::StrCat("0", d)] = {absl::StrCat("oh", kOnes[d]), + std::string(kOnes[d])}; + } + for (int t = 0; t <= 9; ++t) { + map[absl::StrCat(10 + t)] = {std::string(kTeens[t])}; + } + for (int tens = 2; tens <= 9; ++tens) { + map[absl::StrCat(tens, 0)] = {std::string(kTens[tens])}; + for (int ones = 1; ones <= 9; ++ones) { + map[absl::StrCat(tens, ones)] = { + absl::StrCat(kTens[tens], kOnes[ones]), + std::string(kTens[tens])}; + } + } + return map; + }()); + + for (size_t suffix_len = 1; + suffix_len <= std::min(3, canon_prev.size()); ++suffix_len) { + const absl::string_view suffix = + canon_prev.substr(canon_prev.size() - suffix_len); + const auto it = kSpokenNumberMap->find(suffix); + if (it == kSpokenNumberMap->end()) continue; + for (const std::string& cand : it->second) { + if (canon_curr == cand || CloseEnoughCanonical(cand, canon_curr) || + absl::EndsWith(cand, canon_curr)) { + return true; + } + } + } + return false; +} + +// Returns true if `canon_curr` at the start of the current chunk looks like a +// truncated fragment, phonetic variant, or repeat of `canon_prev` that started +// just before the window boundary (e.g. a 1-2 character fragment, a suffix or +// close-enough match, a spoken number suffix matching a numeric token, an +// overlap where a prefix of `canon_curr` of length >= 3 matches a suffix of +// `canon_prev`, or both words having length >= 4 with matching 2-character +// suffix). +bool IsPartialOrMatchingBoundaryWord(absl::string_view canon_prev, + absl::string_view canon_curr) { + if (canon_curr.size() <= 2) return true; + if (absl::EndsWith(canon_prev, canon_curr) || + CloseEnoughCanonical(canon_prev, canon_curr)) { + return true; + } + if (MatchesSpokenNumberSuffix(canon_prev, canon_curr)) { + return true; + } + for (size_t len = std::min(canon_prev.size(), canon_curr.size()); len >= 3; + --len) { + if (absl::EndsWith(canon_prev, canon_curr.substr(0, len))) { + return true; + } + } + return canon_prev.size() >= 4 && canon_curr.size() >= 4 && + canon_prev.substr(canon_prev.size() - 2) == + canon_curr.substr(canon_curr.size() - 2); +} + +// Returns true when a current-only word at `time` starts the window while the +// previous chunk was mid-speech at the boundary (the tail of a word that +// started before `chunk_start` and was cut by the window start). Only previous +// words that started before `chunk_start` can cut the current word at the +// window start, and only when `canon_curr_word` looks like a partial +// suffix/fragment or repeat of that word, so genuinely new words missed by the +// previous chunk are preserved. +bool IsCutAtWindowStart(absl::Span canon_prev_words, + absl::Span prev_timestamps, + absl::string_view canon_curr_word, double chunk_start, + double time, const Tolerances& tol) { + if (time > chunk_start + tol.substitution) return false; + for (size_t idx = 0; idx < prev_timestamps.size(); ++idx) { + const int ts = prev_timestamps[idx]; + if (ts >= chunk_start - tol.match_early && + ts < chunk_start + tol.substitution && ts < time && + IsPartialOrMatchingBoundaryWord(canon_prev_words[idx], + canon_curr_word)) { + return true; + } + } + return false; +} + +// Appends `word` and a monotone (non-decreasing) timestamp to `merged_words` +// and `merged_timestamps`, skipping `word` when it duplicates the trailing +// component of an immediately preceding hyphenated or apostrophe-joined word +// (e.g. "five" after "twenty-five" or "s" after "it's") within +// `max_suffix_gap`. +void AppendMergedWord(std::vector& merged_words, + std::vector& merged_timestamps, + absl::string_view word, int timestamp_ms, + double max_suffix_gap = -1.0) { + if (!merged_words.empty() && merged_words.back().size() > word.size() && + absl::EndsWithIgnoreCase(merged_words.back(), word)) { + const char delim = + merged_words.back()[merged_words.back().size() - word.size() - 1]; + if (delim == '-' || delim == '\'') { + if (max_suffix_gap < 0 || + std::abs(timestamp_ms - merged_timestamps.back()) <= max_suffix_gap) { + return; + } + } + } + const int monotone_ts = + merged_timestamps.empty() + ? timestamp_ms + : std::max(timestamp_ms, merged_timestamps.back()); + merged_words.emplace_back(word); + merged_timestamps.push_back(monotone_ts); +} + +// Walks the overlap alignment `ops` around `pivot` and appends the surviving +// unconfirmed words and non-decreasing timestamps into `merged_words` and +// `merged_timestamps`: +// - Paired words (`kPair`) come from `prev` before `pivot` and `curr` after it. +// - Unpaired `prev` words (`kPrevOnly`) are kept before `pivot`, or after +// `pivot` when `curr` heard nothing at about the same time. +// - Unpaired `curr` words (`kCurrOnly`) are kept after `pivot`, or before +// `pivot` when `prev` neither covered that time nor cut a word at the window +// start. +void MergeAlignedOverlap(absl::Span canon_prev_words, + absl::Span prev_timestamps, + absl::Span prev_ov_words, + absl::Span prev_ov_ts, + absl::Span curr_words, + absl::Span canon_curr_words, + absl::Span curr_timestamps, + absl::Span curr_times, + const std::vector>& close_matrix, + absl::Span ops, double chunk_start, + double pivot, double prev_end_ms, + const Tolerances& tol, + std::vector& merged_words, + std::vector& merged_timestamps) { + const std::vector prev_ov_matched = + FindMatchedPrevOverlapWords(close_matrix, ops); + + merged_words.reserve(prev_ov_words.size() + curr_words.size()); + merged_timestamps.reserve(prev_ov_words.size() + curr_words.size()); + size_t i = 0; + size_t j = 0; + for (AlignOp op : ops) { + switch (op) { + case AlignOp::kPair: { + // Before the pivot the previous chunk had more context, after it the + // current one has. + const bool prefer_prev_numeric = + !close_matrix[i][j] && prev_ov_ts[i] <= pivot + tol.substitution && + !prev_ov_words[i].empty() && prev_ov_words[i].front() >= '0' && + prev_ov_words[i].front() <= '9'; + if (prev_ov_ts[i] < pivot - 1e-4 || prefer_prev_numeric) { + AppendMergedWord(merged_words, merged_timestamps, prev_ov_words[i], + prev_ov_ts[i], tol.match_late); + } else { + AppendMergedWord(merged_words, merged_timestamps, curr_words[j], + curr_timestamps[j], tol.match_late); + } + ++i; + ++j; + break; + } + case AlignOp::kPrevOnly: { + const bool is_unconfirmed_prev_tail = + i + 1 == prev_ov_words.size() && + prev_ov_ts[i] >= prev_end_ms - tol.substitution && + prev_ov_words[i].size() <= 3 && !curr_times.empty(); + if (prev_ov_ts[i] < pivot || + (!is_unconfirmed_prev_tail && + !HasWordWithin(curr_times, prev_ov_ts[i], tol.substitution))) { + AppendMergedWord(merged_words, merged_timestamps, prev_ov_words[i], + prev_ov_ts[i], tol.match_late); + } + ++i; + break; + } + case AlignOp::kCurrOnly: + if (curr_times[j] >= pivot) { + AppendMergedWord(merged_words, merged_timestamps, curr_words[j], + curr_timestamps[j], tol.match_late); + } else if (!IsCoveredByPrev(prev_ov_ts, prev_ov_matched, curr_times[j], + tol) && + !IsCutAtWindowStart(canon_prev_words, prev_timestamps, + canon_curr_words[j], chunk_start, + curr_times[j], tol)) { + AppendMergedWord(merged_words, merged_timestamps, curr_words[j], + static_cast(std::lround(curr_times[j])), + tol.match_late); + } + ++j; + break; + } + } + for (; j < curr_words.size(); ++j) { + AppendMergedWord(merged_words, merged_timestamps, curr_words[j], + curr_timestamps[j], tol.match_late); + } +} + +} // namespace + +TimestampTextMerger::TimestampTextMerger( + Stage>* absl_nonnull detokenizer, + float overlap_ratio, int search_window, float pivot_factor) + : TextMerger(detokenizer), + overlap_ratio_(overlap_ratio), + search_window_(search_window), + pivot_factor_(pivot_factor) {} + +void TimestampTextMerger::ResetInternal() { + prev_words_.clear(); + prev_timestamps_.clear(); + last_confirmed_words_.clear(); + stream_timestamp_offset_ms_ = 0.0; + prev_chunk_end_ms_ = -1.0; + last_chunk_end_ms_ = 0; + prev_is_warm_start_ = false; + consecutive_empty_chunks_ = 0; + confirmed_prefix_size_ = 0; + confirmed_until_ms_ = -1; +} + +absl::Status TimestampTextMerger::ScheduleInternal() { + SetState(State::kRunning); + auto status = Execute(); + SetState(State::kIdle); + return status; +} + +absl::Status TimestampTextMerger::Execute() { + LITERT_ASSIGN_OR_RETURN(auto curr_chunk_words, detokenizer_.GetOutput()); + + const int chunk_start_ms = + static_cast(std::lround(stream_timestamp_offset_ms_)); + std::vector curr_words; + std::vector curr_timestamps; + std::optional max_chunk_timestamp_ms; + bool is_warm_start_chunk = false; + // Whether a word had to be split into several units below. + bool split_word = false; + curr_words.reserve(curr_chunk_words.size()); + for (const auto& word : curr_chunk_words) { + if (word.IsEndOfChunk()) { + is_warm_start_chunk = word.is_warm_start; + if (word.timestamp_ms.has_value()) { + max_chunk_timestamp_ms = word.timestamp_ms.value(); + } + continue; + } + // Align CJK text character by character (see `SplitCjkCharacters`). + // `TokenizerDetokenizer` already emits one word per CJK character; this + // only splits words from detokenizers that do not. + std::vector units = SplitCjkCharacters({word.text}); + split_word |= units.size() > 1; + for (std::string& unit : units) { + if (word.timestamp_ms.has_value()) { + const int abs_ts = word.timestamp_ms.value() + chunk_start_ms; + if (confirmed_until_ms_ >= 0 && abs_ts <= confirmed_until_ms_) { + continue; + } + curr_timestamps.push_back(abs_ts); + } + curr_words.push_back(std::move(unit)); + } + } + // End of the chunk relative to its start; falls back to the last word's + // timestamp (or the previous chunk's duration for a silent chunk) when the + // decoder does not report the end of the chunk. + const int chunk_end_ms = max_chunk_timestamp_ms.value_or( + curr_timestamps.empty() ? last_chunk_end_ms_ + : curr_timestamps.back() - chunk_start_ms); + if (chunk_end_ms > 0) { + last_chunk_end_ms_ = chunk_end_ms; + } + // A split word's timestamp is the onset of its first unit only; using it for + // every unit would confirm the whole word as soon as its onset falls before + // the next chunk, so such chunks are merged by word count instead. + if (split_word) curr_timestamps.clear(); + + if (curr_words.empty()) { + std::string confirmed; + if (!is_warm_start_chunk) { + ++consecutive_empty_chunks_; + const bool is_gated_followup_silence = + !max_chunk_timestamp_ms.has_value() && last_chunk_end_ms_ > 0 && + prev_chunk_end_ms_ > static_cast(last_chunk_end_ms_); + if (!prev_words_.empty() && !prev_is_warm_start_ && + ((prev_chunk_end_ms_ >= 0.0 && + prev_chunk_end_ms_ <= stream_timestamp_offset_ms_) || + consecutive_empty_chunks_ >= 2 || is_gated_followup_silence)) { + if (!prev_timestamps_.empty()) { + confirmed_until_ms_ = + prev_timestamps_.back() + + std::max(1, static_cast(0.08 * last_chunk_end_ms_)); + } + const size_t prefix = + std::min(confirmed_prefix_size_, prev_words_.size()); + confirmed = JoinWithCjkAwareSpacing( + absl::MakeConstSpan(prev_words_).subspan(prefix)); + prev_words_.clear(); + prev_timestamps_.clear(); + confirmed_prefix_size_ = 0; + } + UpdateStreamTimestampOffset(chunk_end_ms); + } + const size_t prefix = std::min(confirmed_prefix_size_, prev_words_.size()); + LogAndPushOutput( + {std::move(confirmed), + prefix >= prev_words_.size() + ? "" + : JoinWithCjkAwareSpacing( + absl::MakeConstSpan(prev_words_).subspan(prefix))}); + return absl::OkStatus(); + } + consecutive_empty_chunks_ = 0; + + if (overlap_ratio_ == 0.0f) { + LogAndPushOutput({JoinWithCjkAwareSpacing(curr_words), ""}); + return absl::OkStatus(); + } + + if (prev_words_.empty() || prev_is_warm_start_) { + prev_words_ = curr_words; + prev_timestamps_ = curr_timestamps; + prev_is_warm_start_ = is_warm_start_chunk; + confirmed_prefix_size_ = 0; + if (!is_warm_start_chunk) { + prev_chunk_end_ms_ = stream_timestamp_offset_ms_ + chunk_end_ms; + UpdateStreamTimestampOffset(chunk_end_ms); + } + LogAndPushOutput({"", JoinWithCjkAwareSpacing(prev_words_)}); + return absl::OkStatus(); + } + + // Chunks whose words all share one timestamp carry no timing information + // unless the decoder reports the end of the chunk. + const bool curr_has_usable_ts = + HasUsableTimestamps(curr_words, curr_timestamps); + const bool use_time = prev_chunk_end_ms_ >= 0.0 && + HasUsableTimestamps(prev_words_, prev_timestamps_) && + curr_has_usable_ts && + (max_chunk_timestamp_ms.has_value() || + HasDistinctTimestamps(prev_timestamps_) || + HasDistinctTimestamps(curr_timestamps)); + if (use_time) { + MergeByTime(curr_words, curr_timestamps); + } else { + if (curr_has_usable_ts) { + ABSL_LOG_FIRST_N(INFO, 5) + << "TimestampTextMerger: falling back to MergeByWordCount " + << "(prev_words=" << prev_words_.size() + << ", prev_timestamps=" << prev_timestamps_.size() << ")"; + } + MergeByWordCount(curr_words, curr_timestamps); + } + prev_chunk_end_ms_ = stream_timestamp_offset_ms_ + chunk_end_ms; + UpdateStreamTimestampOffset(chunk_end_ms); + + const size_t prefix = std::min(confirmed_prefix_size_, prev_words_.size()); + LogAndPushOutput( + {JoinWithCjkAwareSpacing(last_confirmed_words_), + prefix >= prev_words_.size() + ? "" + : JoinWithCjkAwareSpacing( + absl::MakeConstSpan(prev_words_).subspan(prefix))}); + return absl::OkStatus(); +} + +void TimestampTextMerger::MergeByTime(absl::Span curr_words, + absl::Span curr_timestamps) { + if (prev_chunk_end_ms_ <= stream_timestamp_offset_ms_) { + // The window that produced the previous words ends before this chunk + // (e.g. an empty chunk in between): the previous words are final. + const size_t already_confirmed = + std::min(confirmed_prefix_size_, prev_words_.size()); + last_confirmed_words_.assign(prev_words_.begin() + already_confirmed, + prev_words_.end()); + confirmed_prefix_size_ = 0; + prev_words_.assign(curr_words.begin(), curr_words.end()); + prev_timestamps_.assign(curr_timestamps.begin(), curr_timestamps.end()); + return; + } + + const double overlap_len = prev_chunk_end_ms_ - stream_timestamp_offset_ms_; + const double tol_scale = + last_chunk_end_ms_ > 0 + ? std::min(overlap_len, 0.5 * static_cast(last_chunk_end_ms_)) + : overlap_len; + const Tolerances tol = { + .substitution = std::max(1.0, 0.15 * tol_scale), + .match_early = std::max(2.0, 0.25 * tol_scale), + .match_late = std::max(2.0, 0.5 * tol_scale), + }; + + const std::vector canon_prev_words = + CanonicalizeWords(prev_words_); + const std::vector canon_curr_words = + CanonicalizeWords(curr_words); + + // Express the current chunk's word timestamps and both overlap window bounds + // in the previous chunk's word clock by subtracting `shift` (`curr - prev`). + const int shift = EstimateTimestampShift( + canon_prev_words, prev_timestamps_, canon_curr_words, curr_timestamps, + stream_timestamp_offset_ms_, prev_chunk_end_ms_, tol.match_early); + const double chunk_start = stream_timestamp_offset_ms_ - shift; + const double prev_end = prev_chunk_end_ms_ - shift; + const double pivot = chunk_start + pivot_factor_ * (prev_end - chunk_start); + std::vector curr_times; + curr_times.reserve(curr_timestamps.size()); + for (int ts : curr_timestamps) curr_times.push_back(ts - shift); + + // Previous words before the current chunk are final. + size_t num_confirmed = 0; + while (num_confirmed < prev_timestamps_.size() && + prev_timestamps_[num_confirmed] < chunk_start) { + ++num_confirmed; + } + const size_t already_confirmed = + std::min(confirmed_prefix_size_, prev_words_.size()); + num_confirmed = std::max(num_confirmed, already_confirmed); + last_confirmed_words_.assign(prev_words_.begin() + already_confirmed, + prev_words_.begin() + num_confirmed); + confirmed_prefix_size_ = 0; + const auto prev_ov_words = + absl::MakeConstSpan(prev_words_).subspan(num_confirmed); + const auto canon_prev_ov_words = + absl::MakeConstSpan(canon_prev_words).subspan(num_confirmed); + const auto prev_ov_ts = + absl::MakeConstSpan(prev_timestamps_).subspan(num_confirmed); + + // Current words well beyond the previous window are new; the margin lets + // the last words of the previous window, emitted early, find their pair. + size_t num_overlap = 0; + while (num_overlap < curr_times.size() && + curr_times[num_overlap] < prev_end + tol.match_late) { + ++num_overlap; + } + + const auto close_matrix = BuildCloseEnoughMatrix( + canon_prev_ov_words, + absl::MakeConstSpan(canon_curr_words).subspan(0, num_overlap)); + const std::vector ops = AlignOverlap( + close_matrix, prev_ov_ts, + absl::MakeConstSpan(curr_times).subspan(0, num_overlap), tol); + + std::vector merged_words; + std::vector merged_timestamps; + MergeAlignedOverlap(canon_prev_words, prev_timestamps_, prev_ov_words, + prev_ov_ts, curr_words, canon_curr_words, curr_timestamps, + curr_times, close_matrix, ops, chunk_start, pivot, + prev_chunk_end_ms_, tol, merged_words, merged_timestamps); + + ABSL_VLOG(2) << "MergeByTime: shift=" << shift + << " chunk_start=" << chunk_start << " prev_end=" << prev_end + << " pivot=" << pivot << " confirmed=" << num_confirmed + << " overlap prev/curr=" << prev_ov_words.size() << "/" + << num_overlap; + + prev_words_ = std::move(merged_words); + prev_timestamps_ = std::move(merged_timestamps); + if (overlap_ratio_ >= 0.7f) { + const double early_confirm_limit = pivot - tol.substitution; + while (confirmed_prefix_size_ < prev_timestamps_.size() && + prev_timestamps_[confirmed_prefix_size_] < early_confirm_limit) { + last_confirmed_words_.push_back(prev_words_[confirmed_prefix_size_]); + ++confirmed_prefix_size_; + } + } + if (ABSL_VLOG_IS_ON(2)) { + std::string words; + for (size_t k = 0; k < prev_words_.size(); ++k) { + absl::StrAppend(&words, k == 0 ? "" : " ", prev_words_[k], "(", + prev_timestamps_[k], ")"); + } + ABSL_VLOG(2) << "MergeByTime: unconfirmed=" << words; + } +} + +void TimestampTextMerger::MergeByWordCount( + absl::Span curr_words, + absl::Span curr_timestamps) { + if (confirmed_prefix_size_ > 0) { + const size_t drop = std::min(confirmed_prefix_size_, prev_words_.size()); + prev_words_.erase(prev_words_.begin(), prev_words_.begin() + drop); + if (prev_timestamps_.size() >= drop) { + prev_timestamps_.erase(prev_timestamps_.begin(), + prev_timestamps_.begin() + drop); + } else { + prev_timestamps_.clear(); + } + confirmed_prefix_size_ = 0; + } + const bool curr_has_usable_ts = + HasUsableTimestamps(curr_words, curr_timestamps); + if (!prev_words_.empty() && !curr_words.empty()) { + const size_t n_prev = prev_words_.size(); + const size_t n_curr = curr_words.size(); + const size_t min_prev = + (n_prev > 8) + ? std::max( + 1, static_cast(std::max( + 0, static_cast(n_prev * (1.0f - overlap_ratio_)) - + search_window_ - 2))) + : 0; + const size_t max_curr = std::min( + n_curr, static_cast(std::ceil(n_curr * overlap_ratio_)) + + search_window_ + 4); + const std::vector best_run = + FindBestSeamMatchRun(prev_words_, min_prev, curr_words, max_curr); + if (!best_run.empty()) { + const auto [p0, c0] = best_run.front(); + const auto [p_piv, c_piv] = best_run[best_run.size() / 2]; + const int unconfirmed_idx = + std::clamp(static_cast(p0) - static_cast(c0), + static_cast(min_prev), static_cast(p0)); + last_confirmed_words_.assign(prev_words_.begin(), + prev_words_.begin() + unconfirmed_idx); + const size_t prefix_len = p_piv - static_cast(unconfirmed_idx); + std::vector unconfirmed_merged( + prev_words_.begin() + unconfirmed_idx, prev_words_.begin() + p_piv); + if (n_curr - c_piv >= n_prev - p_piv) { + unconfirmed_merged.insert(unconfirmed_merged.end(), + curr_words.begin() + c_piv, curr_words.end()); + } else { + unconfirmed_merged.insert(unconfirmed_merged.end(), + prev_words_.begin() + p_piv, + prev_words_.end()); + } + prev_words_ = std::move(unconfirmed_merged); + prev_timestamps_.clear(); + if (curr_has_usable_ts) { + prev_timestamps_.reserve(prev_words_.size()); + for (size_t k = 0; k < prev_words_.size(); ++k) { + const int c_idx = + std::clamp(static_cast(c_piv) + static_cast(k) - + static_cast(prefix_len), + 0, static_cast(n_curr) - 1); + prev_timestamps_.push_back(curr_timestamps[c_idx]); + } + } + return; + } + } + + last_confirmed_words_ = std::move(prev_words_); + prev_words_.assign(curr_words.begin(), curr_words.end()); + if (curr_has_usable_ts) { + prev_timestamps_.assign(curr_timestamps.begin(), curr_timestamps.end()); + } else { + prev_timestamps_.clear(); + } +} + +absl::Status TimestampTextMerger::FlushInternal() { + const size_t prefix = std::min(confirmed_prefix_size_, prev_words_.size()); + if (prefix < prev_words_.size()) { + MergeResult result = {JoinWithCjkAwareSpacing( + absl::MakeConstSpan(prev_words_).subspan(prefix)), + ""}; + prev_words_.clear(); + prev_timestamps_.clear(); + last_confirmed_words_.clear(); + confirmed_prefix_size_ = 0; + confirmed_until_ms_ = -1; + prev_chunk_end_ms_ = -1.0; + last_chunk_end_ms_ = 0; + LogAndPushOutput(std::move(result)); + } else { + prev_words_.clear(); + prev_timestamps_.clear(); + last_confirmed_words_.clear(); + confirmed_prefix_size_ = 0; + confirmed_until_ms_ = -1; + prev_chunk_end_ms_ = -1.0; + last_chunk_end_ms_ = 0; + } + return absl::OkStatus(); +} + +void TimestampTextMerger::UpdateStreamTimestampOffset(int chunk_end_ms) { + if (overlap_ratio_ <= 0.0f) return; + // Kept fractional: with encoder-frame timestamps the step is not a whole + // number of frames, and truncating it drifts by a frame every few chunks. + if (chunk_end_ms > 0) { + stream_timestamp_offset_ms_ += chunk_end_ms * (1.0 - overlap_ratio_); + } +} + +void TimestampTextMerger::LogAndPushOutput(MergeResult output) { + ABSL_VLOG(1) << "Merged text: confirmed=" << output.confirmed_text; + ABSL_VLOG(1) << "Merged text: unconfirmed=" << output.unconfirmed_text; + PushOutput(std::move(output)); +} + +} // namespace litert::omni::asr diff --git a/tools/gpu_environment_teardown.py b/tools/gpu_environment_teardown.py index 6d1a4f0..1005dfc 100644 --- a/tools/gpu_environment_teardown.py +++ b/tools/gpu_environment_teardown.py @@ -87,10 +87,8 @@ def check_initialize_disassembly(disassembly: str) -> None: raise RuntimeError( "GpuEnvironment::Initialize sets up OpenCL before it records the " "environment options, so an OpenCL load failure drops the WebGPU " - "destroy callback and engine deletes leak graphics memory. Add the " - "pinned LiteRT commit to LITERT_REFS_WITHOUT_GPU_TEARDOWN_ORDERING " - "in tools/build_upstream_runtime.py after confirming that " - "native/bridge/litert_gpu_environment_destroy_callback.patch applies." + "destroy callback and engine deletes leak graphics memory. " + "Requalify the pinned LiteRT GPU environment initialization." ) diff --git a/tools/huggingface_token_bytes_patch.py b/tools/huggingface_token_bytes_patch.py index cbbd0d8..57889ba 100644 --- a/tools/huggingface_token_bytes_patch.py +++ b/tools/huggingface_token_bytes_patch.py @@ -1,44 +1,11 @@ """Identity and fail-closed application of the HF ByteLevel grammar fix (#100).""" import hashlib -import re from pathlib import Path -from source_patch_utils import apply_source_patch +from source_patch_utils import active_source_carries, apply_source_patch -PATCH_PATH = "native/bridge/huggingface_token_bytes_v019.patch" -AUDITED_TAGS = frozenset({"v0.19.0", "v0.19.1", "v0.20.0"}) -# LF-normalized upstream v0.19.0 / 83ce6067 preimages and patched postimages; -# v0.19.1 / 7a03724c leaves every preimage unchanged. +PATCH_PATH = "native/bridge/huggingface_token_bytes_v020.patch" SOURCES = { - "support/tokenizer/tokenizer.h": ( - "f80f9685c276c303bb3110203069ece92bcc61276db537baee50599eed2ad1da", - "b0ca05aa33fc0a6d7b735806383970e2f24e52d55db6c2bb8192b7123a20ae44", - ), - "support/tokenizer/huggingface_tokenizer.h": ( - "f5ef2a52bc703ddc8b1ad620a0e7f92e1f0e4a874cbffdb939eeaa99d3246715", - "9e38b5f25c0ee9403682e9794f88e03811e74e6c570fe70ce99c5f5ea947f0c5", - ), - "support/tokenizer/huggingface_tokenizer.cc": ( - "922ad95701de97e2aedf8514244082d6c1befbced46b8ed59bcc6998d9e985a2", - "d40a250600d159b25de4b2a5da6afc05695814c8819c3a463616876cb480aa82", - ), - "support/tokenizer/BUILD": ( - "91ab9cb6ee4b714140cd5c4bfffd1524d7eb5ae06869f32ad7214cbe5a3cbdef", - "a38d0653c97324d3e17554e0584ca137775f32e875d8418ae7a0db60be3e5523", - ), - "runtime/components/constrained_decoding/llg_constraint_provider.cc": ( - "91e0174e024b8787cdf83b21ca7eaae0718ba140e12f6e7a82bbd6193078e5ce", - "ce7aef5712d1d3c6eaa632a964f034776aa81216cbdbd8278dec3793bb484159", - ), - "runtime/components/constrained_decoding/BUILD": ( - "9ee6588548f9ec54ed1418ff20945e289b60308606bee27e7ad432944b969c04", - "b16dc8bc86997a7a276c70afc75ad6be1ba70938f31ef4db53bfcc6a9025dd7d", - ), -} - - -V020_PATCH_PATH = "native/bridge/huggingface_token_bytes_v020.patch" -V020_SOURCES = { "runtime/components/constrained_decoding/BUILD": ( "dfce389070058c835975ca2f76d4858830156928b12131c53a5933cb522661f8", "a73f1ba0602ed08e6b6c63042be557fed3a6d1815d92cf588d96a8d14cde4b6b", @@ -66,38 +33,20 @@ } -def sources_for(tag: str) -> dict[str, tuple[str, str]]: - return V020_SOURCES if tag == "v0.20.0" else SOURCES - - -def patch_path_for(tag: str) -> str: - return V020_PATCH_PATH if tag == "v0.20.0" else PATCH_PATH - - -def require_token_bytes_patch_decision(tag: str) -> bool: - version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", tag) - if version and tuple(map(int, version.groups())) < (0, 19, 0): - return False - if tag in AUDITED_TAGS: - return True - raise RuntimeError(f"HuggingFace token bytes have no explicit decision for {tag}; " - "requalify #100 in docs/upstream_patch_audit.md") - - def _digest(path: Path) -> str: return hashlib.sha256(path.read_bytes().replace(b"\r\n", b"\n")).hexdigest() def apply(source_root: Path, tag: str) -> None: - if not require_token_bytes_patch_decision(tag): + if not active_source_carries(tag): return - sources = sources_for(tag) + sources = SOURCES digests = {name: _digest(source_root / name) for name in sources} if all(digests[name] == post for name, (_, post) in sources.items()): return if any(digests[name] != pre for name, (pre, _) in sources.items()): raise RuntimeError("Tokenizer or grammar source changed; requalify #100 token bytes patch") - patch = Path(__file__).resolve().parents[1] / patch_path_for(tag) + patch = Path(__file__).resolve().parents[1] / PATCH_PATH apply_source_patch(source_root, patch, ignore_space_change=True) mismatches = [name for name, (_, post) in sources.items() if _digest(source_root / name) != post] @@ -108,12 +57,12 @@ def apply(source_root: Path, tag: str) -> None: def token_bytes_patch_manifest(tag: str) -> list[dict]: - if not require_token_bytes_patch_decision(tag): + if not active_source_carries(tag): return [] digest = hashlib.sha256( - (Path(__file__).resolve().parents[1] / patch_path_for(tag)).read_bytes()).hexdigest() + (Path(__file__).resolve().parents[1] / PATCH_PATH).read_bytes()).hexdigest() return [{ - "id": "huggingface-token-bytes", "path": patch_path_for(tag), "sha256": digest, + "id": "huggingface-token-bytes", "path": PATCH_PATH, "sha256": digest, "source": name, "preimageSha256Lf": pre, "postimageSha256Lf": post, "scope": "source-built runtimes only; excludes official upstream prebuilts", - } for name, (pre, post) in sources_for(tag).items()] + } for name, (pre, post) in SOURCES.items()] diff --git a/tools/litert_cpu_options_identifier_patch.py b/tools/litert_cpu_options_identifier_patch.py deleted file mode 100644 index eb8090c..0000000 --- a/tools/litert_cpu_options_identifier_patch.py +++ /dev/null @@ -1,89 +0,0 @@ -"""Identity of the carried LiteRT CPU options identifier rollback (#89).""" -import hashlib -import re -from pathlib import Path - -PATCH_PATH = "native/bridge/litert_cpu_options_identifier.patch" -AUDITED_TAGS = frozenset({"v0.18.1"}) -# v0.19.0 ships Linux and Windows prebuilt libLiteRt that read "cpu_options", -# the same identifier its pinned LiteRT dcb657e8 writes. v0.19.1 keeps both the -# LiteRT pin and those prebuilts. -UPSTREAM_FIX_TAGS = frozenset({"v0.19.0", "v0.19.1", "v0.20.0"}) -# LiteRT 724a247cc5 renamed the CPU options identifier from "xnnpack" to -# "cpu_options". v0.18.1 pins LiteRT ca21dc99, which has the rename, but still -# ships the 2026-09-28 prebuilt libLiteRt from before it. Linux and Windows -# hosts link that runtime, whose XNNPACK accelerator looks up only "xnnpack", -# so it dropped every CPU option, including the thread count. Static runtimes -# read the identifier from the same function, so the patch is neutral there. -RENAME_COMMIT = "724a247cc5" -LITERT_REF = "ca21dc99de51c76bdcc572afeea1dd937d3c9e5c" -LITERT_ARCHIVE_SHA256 = "d3c0455b405fadc597c840c8d708ced4f2a89c78eae21d9c0252f744b94c7fbc" -SOURCE = "litert/c/options/litert_cpu_options.cc" -# LF-normalized (preimage, postimage) SHA-256 of SOURCE. -SOURCES = { - SOURCE: ( - "ecfa9e2523dfae8c1417c12e4bb02c1b7b3c6bcaa6f93310ff4c859978485b09", - "bb7008295ad9e0a3ccc6a2a0119c14e7cafa481792512dc4bed2b06890347cb9", - ), -} -# Upstream v0.18.1 prebuilt runtimes audited to read "xnnpack". -DYNAMIC_RUNTIMES = { - ("linux", "arm64"): ( - "linux_arm64/libLiteRt.so", - "989bccd9c950ad8ae8fa40a3febb54490cc7960ad81d260b36c9480574e8092a", - ), - ("linux", "x64"): ( - "linux_x86_64/libLiteRt.so", - "88beda3e49caf68332d4b2ff418f7f42f34830e4ec54587f3b3e381d4462ab2d", - ), - ("windows", "x64"): ( - "windows_x86_64/libLiteRt.dll", - "d027bceb59db9402abe3b20f61e3e6eab329b4f7c5665e7228b64871e7164c8a", - ), -} - - -def require_cpu_options_identifier_patch_decision(compatibility_tag: str) -> bool: - """Returns whether the rollback applies; newer sources need a decision.""" - if compatibility_tag in AUDITED_TAGS: - return True - if compatibility_tag in UPSTREAM_FIX_TAGS: - return False - version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", compatibility_tag) - if version and tuple(map(int, version.groups())) <= (0, 18, 0): - return False - raise RuntimeError( - f"LiteRT CPU options identifier rollback has no explicit decision for " - f"{compatibility_tag}; v0.19+ hosts compile LiteRT in (#111), so the " - "rollback is needed only if a host links a separate libLiteRt that reads " - "another identifier than the pinned LiteRT writes. Record the decision in " - "tools/litert_cpu_options_identifier_patch.py and " - "docs/upstream_patch_audit.md") - - -def verify_dynamic_runtime(prebuilt_root: Path, platform: str, arch: str) -> None: - """Fails unless a dynamic host links the prebuilt runtime this patch targets.""" - if (platform, arch) not in DYNAMIC_RUNTIMES: - return - name, digest = DYNAMIC_RUNTIMES[(platform, arch)] - runtime = prebuilt_root / name - if not runtime.is_file() or hashlib.sha256(runtime.read_bytes()).hexdigest() != digest: - raise RuntimeError( - f"Prebuilt {name} changed; requalify the CPU options identifier rollback") - - -def cpu_options_identifier_patch_manifest(compatibility_tag: str) -> list[dict]: - if not require_cpu_options_identifier_patch_decision(compatibility_tag): - return [] - patch_sha256 = hashlib.sha256( - (Path(__file__).resolve().parents[1] / PATCH_PATH).read_bytes() - ).hexdigest() - return [{ - "id": "litert-cpu-options-identifier", - "path": PATCH_PATH, - "sha256": patch_sha256, - "source": f"LiteRT@{LITERT_REF}/{source}", - "preimageSha256Lf": preimage, - "postimageSha256Lf": postimage, - "scope": "source-built runtimes only; excludes official upstream prebuilts", - } for source, (preimage, postimage) in SOURCES.items()] diff --git a/tools/litert_lm_finish_reason_smoke.py b/tools/litert_lm_finish_reason_smoke.py index 81789b4..fffe30d 100644 --- a/tools/litert_lm_finish_reason_smoke.py +++ b/tools/litert_lm_finish_reason_smoke.py @@ -20,7 +20,7 @@ from litert_lm_c_api import CApi from litert_lm_symbols import in_process_litert_abi_version -from stream_finish_reason_patch import require_finish_reason_patch_decision +from source_patch_utils import active_source_carries FINISH_REASONS = { 0: "unknown", @@ -183,7 +183,9 @@ def mismatches(results: list[dict[str, object]]) -> list[str]: def expected_abi_version(upstream_tag: str) -> int: - return 1 if require_finish_reason_patch_decision(upstream_tag) else 0 + if not active_source_carries(upstream_tag): + raise RuntimeError("Use the historical native release ref to qualify LiteRT-LM before v0.20.0") + return 1 def in_process_litert_matches(library, upstream_tag: str) -> bool: diff --git a/tools/litert_stage_spatial_tensors_patch.py b/tools/litert_stage_spatial_tensors_patch.py index 38b36a6..e65736e 100644 --- a/tools/litert_stage_spatial_tensors_patch.py +++ b/tools/litert_stage_spatial_tensors_patch.py @@ -1,35 +1,14 @@ """Identity of the LiteRT background command-buffer binding backport.""" import hashlib -import re from pathlib import Path -PATCH_PATH = "native/bridge/litert_stage_spatial_tensors.patch" +from source_patch_utils import active_source_carries + UPSTREAM_FIX = "aa9e40cd5e2d892b3a5d8579a7ec6faa696e321e" -LITERT_REF = "dcb657e8a537b2dc944e53e14c7eb43bcd9ededa" -LITERT_ARCHIVE_SHA256 = "601bada4d86862a21105ca656f02a22483d2b5733b9932ce997e4b1f59bf8e52" +PATCH_PATH = "native/bridge/litert_stage_spatial_tensors_v020.patch" +LITERT_REF = "bf49eb62406d15948261a840c9dcd8e4f13b478c" +LITERT_ARCHIVE_SHA256 = "f5ee44f21843bc6634c02d20d5abb2e4dc0feb83d702b73b5073f10c008231ba" SOURCES = { - "ml_drift_delegate/delegate/gpu_backend_vulkan.cc": ( - "94510294e45a568440e87366facbae6294a1087a52bbbcbab05e5f6ceec6d3dd", - "ee5943a90770691b5e959152c02aaad642d9f6b42ddfbe08b1e3cb79bf8e614a", - ), - "ml_drift_delegate/delegate/gpu_backend_vulkan.h": ( - "10482b2f4cc84e5db67f7385499307dcc930ffa24bfba397e42d2299808d9736", - "0695e45c94da94b87bbb91325b37ff0162c48deaaf5755abeaa51e68f6d1f0ed", - ), - "ml_drift_delegate/delegate/gpu_backend_webgpu.cc": ( - "633b5483a3b25660135e5fff01edbebf43854c547726b85583a0fe4906fb7b8e", - "d2d0fc662b7dfd0b9fa5f95c04ada48f414b08c8f350a9e1169022371d3df968", - ), - "ml_drift_delegate/delegate/gpu_backend_webgpu.h": ( - "bf318922fa10a4de702c9ac39212188e90809a0f9de918c29480c5317229c65c", - "5b756ac60ad2f183eae4981679bf6235befb2e70b82d6ad0807f7831277706b4", - ), -} - -V020_PATCH_PATH = "native/bridge/litert_stage_spatial_tensors_v020.patch" -V020_LITERT_REF = "bf49eb62406d15948261a840c9dcd8e4f13b478c" -V020_LITERT_ARCHIVE_SHA256 = "f5ee44f21843bc6634c02d20d5abb2e4dc0feb83d702b73b5073f10c008231ba" -V020_SOURCES = { "ml_drift_delegate/delegate/gpu_backend_vulkan.cc": ( "94510294e45a568440e87366facbae6294a1087a52bbbcbab05e5f6ceec6d3dd", "ee5943a90770691b5e959152c02aaad642d9f6b42ddfbe08b1e3cb79bf8e614a", @@ -49,38 +28,19 @@ } -def identity_for(compatibility_tag: str) -> tuple[str, str, str, dict[str, tuple[str, str]]]: - if compatibility_tag == "v0.20.0": - return V020_PATCH_PATH, V020_LITERT_REF, V020_LITERT_ARCHIVE_SHA256, V020_SOURCES - return PATCH_PATH, LITERT_REF, LITERT_ARCHIVE_SHA256, SOURCES - - -def require_stage_spatial_tensors_patch_decision(compatibility_tag: str) -> bool: - if compatibility_tag in {"v0.19.1", "v0.20.0"}: - return True - version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", compatibility_tag) - if version and tuple(map(int, version.groups())) <= (0, 19, 0): - return False - raise RuntimeError( - f"LiteRT spatial tensor staging has no explicit decision for {compatibility_tag}; " - "requalify the backport or document its retirement in docs/v019_qualification.md" - ) - - def stage_spatial_tensors_patch_manifest(compatibility_tag: str) -> list[dict]: - if not require_stage_spatial_tensors_patch_decision(compatibility_tag): + if not active_source_carries(compatibility_tag): return [] - patch_path, litert_ref, _, sources = identity_for(compatibility_tag) patch_sha256 = hashlib.sha256( - (Path(__file__).resolve().parents[1] / patch_path).read_bytes() + (Path(__file__).resolve().parents[1] / PATCH_PATH).read_bytes() ).hexdigest() return [{ "id": "litert-stage-spatial-tensors", - "path": patch_path, + "path": PATCH_PATH, "sha256": patch_sha256, - "source": f"LiteRT@{litert_ref}/{source}", + "source": f"LiteRT@{LITERT_REF}/{source}", "preimageSha256Lf": preimage, "postimageSha256Lf": postimage, "scope": ("source-built runtimes only; excludes official upstream prebuilts; " f"backports google-ai-edge/LiteRT@{UPSTREAM_FIX}"), - } for source, (preimage, postimage) in sources.items()] + } for source, (preimage, postimage) in SOURCES.items()] diff --git a/tools/prebuilt_overrides.py b/tools/prebuilt_overrides.py index ef49207..b99724c 100644 --- a/tools/prebuilt_overrides.py +++ b/tools/prebuilt_overrides.py @@ -26,9 +26,6 @@ def target_path(self) -> str: "https://media.githubusercontent.com/media/google-ai-edge/LiteRT-LM" ) -V0_15_ANDROID_SAMPLER_FIX_COMMIT = ( - "8bee4dddc3794958b4bdd8a3a4ba75bcb71f6fbb" -) ANDROID_DAWN_ROLLBACK_COMMIT = ( "f73637c57f0940b53da184e0d5adfc52a4e55eef" ) @@ -56,60 +53,45 @@ def target_path(self) -> str: ), ) -PREBUILT_OVERRIDES: dict[str, tuple[PrebuiltOverride, ...]] = { - "v0.15.0": ( - PrebuiltOverride( - upstream_target="android_arm64", - platform="android", - arch="arm64", - filename="libLiteRtTopKOpenClSampler.so", - source_commit=V0_15_ANDROID_SAMPLER_FIX_COMMIT, - sha256=( - "4404dc68786460602685cab62ddfa29035e9cfc38bb4550dec15abaaa1302a82" - ), - ), - PrebuiltOverride( - upstream_target="android_x86_64", - platform="android", - arch="x64", - filename="libLiteRtTopKOpenClSampler.so", - source_commit=V0_15_ANDROID_SAMPLER_FIX_COMMIT, - sha256=( - "747ca5ed6a175fb4c2854ccee1d6ad97f11fe14d9e0d2b0c1710e1435376d51e" - ), - ), - *ANDROID_DAWN_ROLLBACKS, - ), - "v0.16.0": ANDROID_DAWN_ROLLBACKS, - # v0.16.1 is a metadata-only release of the exact v0.16.0 source commit. - # Development builds using it as their compatibility baseline keep the - # validated Dawn correction until new device evidence retires it. - "v0.16.1": ANDROID_DAWN_ROLLBACKS, - # v0.17 still loses the Vulkan device on Pixel Mali-G715. Keep the - # checksum-pinned correction; do not retire it without device evidence. - "v0.17.0": ANDROID_DAWN_ROLLBACKS, - # v0.17.1 changes tool-call integer handling, not the Android Dawn inputs. - # Preserve the correction until matching device evidence retires it. - "v0.17.1": ANDROID_DAWN_ROLLBACKS, - # Stock v0.18 still loses the Vulkan device on Pixel Mali-G715. - # A single-library comparison restores inference with the pinned Dawn. - "v0.18.0": ANDROID_DAWN_ROLLBACKS, - # v0.18.1 updates LiteRT/provider dependencies but not Dawn payloads. - # No affected Pixel/Mali device requalification permits retirement. - "v0.18.1": ANDROID_DAWN_ROLLBACKS, - # v0.19.0 rebuilds Dawn and the accelerator. Keep the correction, whose - # exports cover the candidate's imports, until a Pixel Mali-G715 run retires it. - "v0.19.0": ANDROID_DAWN_ROLLBACKS, - # v0.19.1 ships the same prebuilt Dawn and accelerator payloads as v0.19.0. - "v0.19.1": ANDROID_DAWN_ROLLBACKS, - "v0.20.0": ANDROID_DAWN_ROLLBACKS, -} - def prebuilt_overrides(upstream_tag: str | None) -> tuple[PrebuiltOverride, ...]: - if upstream_tag is None: - return () - return PREBUILT_OVERRIDES.get(upstream_tag, ()) + return ANDROID_DAWN_ROLLBACKS if upstream_tag == "v0.20.0" else () + + +def _recorded_overrides(upstream_tag: str | None) -> tuple[PrebuiltOverride, ...]: + # Published provenance and the frozen schema-2 fixture still consume these + # records. Historical source builds use their own release refs. + if upstream_tag == "v0.15.0": + sampler_commit = "8bee4dddc3794958b4bdd8a3a4ba75bcb71f6fbb" + return ( + PrebuiltOverride( + upstream_target="android_arm64", + platform="android", + arch="arm64", + filename="libLiteRtTopKOpenClSampler.so", + source_commit=sampler_commit, + sha256=( + "4404dc68786460602685cab62ddfa29035e9cfc38bb4550dec15abaaa1302a82" + ), + ), + PrebuiltOverride( + upstream_target="android_x86_64", + platform="android", + arch="x64", + filename="libLiteRtTopKOpenClSampler.so", + source_commit=sampler_commit, + sha256=( + "747ca5ed6a175fb4c2854ccee1d6ad97f11fe14d9e0d2b0c1710e1435376d51e" + ), + ), + *ANDROID_DAWN_ROLLBACKS, + ) + if upstream_tag in { + "v0.16.0", "v0.16.1", "v0.17.0", "v0.17.1", "v0.18.0", "v0.18.1", + "v0.19.0", "v0.19.1", + }: + return ANDROID_DAWN_ROLLBACKS + return prebuilt_overrides(upstream_tag) def prebuilt_override_manifest(upstream_tag: str | None) -> list[dict[str, str]]: @@ -121,5 +103,5 @@ def prebuilt_override_manifest(upstream_tag: str | None) -> list[dict[str, str]] "targetPath": override.target_path, "sha256": override.sha256, } - for override in prebuilt_overrides(upstream_tag) + for override in _recorded_overrides(upstream_tag) ] diff --git a/tools/qualify_asr_untimed_overlap.py b/tools/qualify_asr_untimed_overlap.py index 4f3c05e..2ddf2e2 100644 --- a/tools/qualify_asr_untimed_overlap.py +++ b/tools/qualify_asr_untimed_overlap.py @@ -12,7 +12,7 @@ import sys from pathlib import Path -from asr_overlap_patch import merger_source +from asr_overlap_patch import MERGER_SOURCE from build_upstream_runtime import patch_asr_untimed_overlap REPO = Path(__file__).resolve().parents[1] @@ -20,7 +20,7 @@ from sim import utter, windows # noqa: E402 -QUALIFIED_TAG = "v0.19.0" +QUALIFIED_TAG = "v0.20.0" ABSL_PACKAGES = ( "absl_status", "absl_statusor", "absl_status_macros", "absl_strings", "absl_synchronization", "absl_log_internal_message", "absl_vlog_config_internal", @@ -51,15 +51,14 @@ def compiler_command(source: Path, work: Path) -> list[str]: @lru_cache(maxsize=None) -def compile_shared_objects(source: Path, work: Path, tag: str) -> tuple[Path, ...]: +def compile_shared_objects(source: Path, work: Path) -> tuple[Path, ...]: # Reuse only within this process, never stale objects from a previous run. # Every mutant still compiles its own actual merger implementation. outputs = [] - merger_dir = Path(merger_source(tag)).parent - text_utils = "omni/utils" if tag == "v0.20.0" else "omni/base" + merger_dir = Path(MERGER_SOURCE).parent for name, unit in (("driver", REPO / "native/bridge/litert_lm_asr_merger_test.cc"), ("levenshtein", source / merger_dir / "levenshtein_align.cc"), - ("text_utils", source / text_utils / "text_utils.cc")): + ("text_utils", source / "omni/utils/text_utils.cc")): output = work / (name + ".o") subprocess.run([*compiler_command(source, work), "-c", str(unit), "-o", str(output)], check=True) @@ -67,8 +66,8 @@ def compile_shared_objects(source: Path, work: Path, tag: str) -> tuple[Path, .. return tuple(outputs) -def compile_driver(source: Path, work: Path, merger: Path, output: Path, tag: str) -> None: - shared = compile_shared_objects(source, work, tag) +def compile_driver(source: Path, work: Path, merger: Path, output: Path) -> None: + shared = compile_shared_objects(source, work) _, ldflags = abseil_flags() subprocess.run([*compiler_command(source, work), str(merger), *map(str, shared), *ldflags, "-o", str(output)], check=True) @@ -77,7 +76,7 @@ def compile_driver(source: Path, work: Path, merger: Path, output: Path, tag: st def compile_replays(source: Path, work: Path, tag: str) -> tuple[Path, Path]: work.mkdir(parents=True, exist_ok=True) patched = work / "patched" - merger = merger_source(tag) + merger = MERGER_SOURCE target = patched / merger target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(source / merger, target) @@ -91,7 +90,7 @@ def compile_replays(source: Path, work: Path, tag: str) -> tuple[Path, Path]: outputs = [] for name, unit in (("upstream", source / merger), ("fixed", target)): output = work / name - compile_driver(source, work, unit, output, tag) + compile_driver(source, work, unit, output) outputs.append(output) subprocess.run([str(outputs[1])], check=True) return tuple(outputs) @@ -231,7 +230,7 @@ def check_mutations(source: Path, work: Path, upstream: Path, fixed: Path, clean_cache: dict, equivalence_count: int, tag: str) -> dict: # Extends audit mut/mut.py. Mutations change the real merger source, then # compile and run the same native tests and negative differential controls. - text = (work / "patched" / merger_source(tag)).read_text() + text = (work / "patched" / MERGER_SOURCE).read_text() mutations = { "M4_one_word": ("min_anchor_words = 2", "min_anchor_words = 1"), "M5_three_words": ("min_anchor_words = 2", "min_anchor_words = 3"), @@ -265,7 +264,7 @@ def check_mutations(source: Path, work: Path, upstream: Path, fixed: Path, mutant = work / (name + ".cc") mutant.write_text(variant) binary = work / name - compile_driver(source, work, mutant, binary, tag) + compile_driver(source, work, mutant, binary) native = subprocess.run([str(binary)], capture_output=True, text=True) negative = False try: diff --git a/tools/qualify_huggingface_token_bytes.py b/tools/qualify_huggingface_token_bytes.py index 825b701..38c819f 100644 --- a/tools/qualify_huggingface_token_bytes.py +++ b/tools/qualify_huggingface_token_bytes.py @@ -11,7 +11,7 @@ import shutil import subprocess -from huggingface_token_bytes_patch import apply as apply_token_bytes_patch, sources_for +from huggingface_token_bytes_patch import apply as apply_token_bytes_patch, SOURCES REPO = Path(__file__).resolve().parents[1] @@ -80,7 +80,7 @@ def mutation_controls(compiler: str, cflags: list[str], work_dir: Path) -> list[ def qualify(work_dir: Path, tokenizer_json: Path | None = None, source_root: Path | None = None, mutations: bool = False, *, - upstream_tag: str = "v0.19.0", runtime_library: Path | None = None, + upstream_tag: str = "v0.20.0", runtime_library: Path | None = None, llguidance_include: Path | None = None, schema_json: Path | None = None, observed_output: Path | None = None) -> dict: @@ -129,7 +129,7 @@ def qualify(work_dir: Path, tokenizer_json: Path | None = None, patched = work_dir / "patched" headers = ["runtime/components/constrained_decoding/" + name for name in ("llg_constraint_provider.h", "llg_constraint_config.h", "constraint_provider.h")] - for name in [*sources_for(upstream_tag), *headers]: + for name in [*SOURCES, *headers]: target = patched / name target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(source_root / name, target) @@ -264,7 +264,7 @@ def main() -> None: parser.add_argument("--work-dir", type=Path, required=True) parser.add_argument("--tokenizer-json", type=Path) parser.add_argument("--source-root", type=Path) - parser.add_argument("--upstream-tag", default="v0.19.0") + parser.add_argument("--upstream-tag", default="v0.20.0") parser.add_argument("--mutations", action="store_true") parser.add_argument("--runtime-library", type=Path) parser.add_argument("--llguidance-include", type=Path) diff --git a/tools/source_patch_utils.py b/tools/source_patch_utils.py index e1f25a0..e667301 100644 --- a/tools/source_patch_utils.py +++ b/tools/source_patch_utils.py @@ -1,6 +1,7 @@ """Apply audited patches relative to the upstream source root.""" import os +import re import subprocess from pathlib import Path @@ -14,3 +15,13 @@ def apply_source_patch( args.append(str(patch_file)) subprocess.run(["git", "apply", "--check", *args], check=True, cwd=source_root, env=env) subprocess.run(["git", "apply", *args], check=True, cwd=source_root, env=env) + + +def active_source_carries(tag: str) -> bool: + """Older release refs own their carries. A newer baseline requires requalification.""" + if tag == "v0.20.0": + return True + version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", tag) + if version and tuple(map(int, version.groups())) < (0, 20, 0): + return False + raise RuntimeError(f"LiteRT-LM source carries have no explicit decision for {tag}") diff --git a/tools/step_zero_state_patch.py b/tools/step_zero_state_patch.py deleted file mode 100644 index 5e6ad75..0000000 --- a/tools/step_zero_state_patch.py +++ /dev/null @@ -1,58 +0,0 @@ -"""Version-bound step-zero reset and macOS linear-attention sampler policy.""" -import hashlib -import re -from pathlib import Path - -from source_patch_utils import apply_source_patch - -PATCH_PATH = "native/bridge/step_zero_state_v0191.patch" -SOURCE = "runtime/executor/llm_litert_compiled_model_executor.cc" -PREIMAGE = "5e6898eb07178719c554ed49e4bc79d891badea4ad0576d00af54ef1bd8dbb4c" -POSTIMAGE = "b2c73fbcb400654072bf926dbaa3b81e252acf750f8fc1a60dd0b51df84d890d" - - - -def applies(tag: str) -> bool: - if tag == "v0.20.0": - return False - if tag == "v0.19.1": - return True - version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", tag) - if version and tuple(map(int, version.groups())) < (0, 19, 1): - return False - raise RuntimeError(f"Step-zero state has no explicit decision for {tag}; " - "requalify the carry in docs/v019_qualification.md") - - -def _digest(path: Path) -> str: - return hashlib.sha256(path.read_bytes().replace(b"\r\n", b"\n")).hexdigest() - - -def apply(source_root: Path, tag: str) -> None: - if not applies(tag): - return - path = source_root / SOURCE - digest = _digest(path) - if digest == POSTIMAGE: - return - if digest != PREIMAGE: - raise RuntimeError("Executor source changed; requalify the step-zero state patch") - patch = Path(__file__).resolve().parents[1] / PATCH_PATH - apply_source_patch(source_root, patch, ignore_space_change=True) - if _digest(path) != POSTIMAGE: - raise RuntimeError("Executor step-zero state postimage mismatch") - - -def manifest(tag: str) -> list[dict]: - if not applies(tag): - return [] - patch = Path(__file__).resolve().parents[1] / PATCH_PATH - return [{ - "id": "step-zero-state", - "path": PATCH_PATH, - "sha256": hashlib.sha256(patch.read_bytes()).hexdigest(), - "source": SOURCE, - "preimageSha256Lf": PREIMAGE, - "postimageSha256Lf": POSTIMAGE, - "scope": "source-built runtimes only; excludes official upstream prebuilts", - }] diff --git a/tools/stream_finish_reason_patch.py b/tools/stream_finish_reason_patch.py index 4d6e3f0..1d04199 100644 --- a/tools/stream_finish_reason_patch.py +++ b/tools/stream_finish_reason_patch.py @@ -1,75 +1,12 @@ """Identity of the carried stream finish-reason patch (#78).""" import hashlib -import re from pathlib import Path -PATCH_PATH = "native/bridge/stream_finish_reason.patch" +from source_patch_utils import active_source_carries + BAZEL_DEFINE = "--define=litert_lm_finish_reason_api=true" -# v0.18.1 changes dependencies only; all six preimages equal v0.18.0. -AUDITED_FINISH_REASON_TAGS = frozenset({"v0.18.0", "v0.18.1", "v0.19.0", "v0.19.1", "v0.20.0"}) -# LF-normalized (preimage, postimage) SHA-256 per patched v0.18.0 source. +PATCH_PATH = "native/bridge/stream_finish_reason_v020.patch" SOURCES = { - "c/conversation.cc": ( - "17ad21e19c750c3216af7ca634dbbc58e8e0ca17445ce172fd607764b169cbf2", - "60cd715a7d56e7f6b66a50b0d18f34a346f979fb09310835e1b1232a64a888ba", - ), - "c/engine_internal.h": ( - "7a4f6796238ab25547f2a2a791dddcede273e422e90837b18ae4fe277f522e49", - "4df4517a4e9bfedcce915dd3ee394dff3813f9d89501122d97771d5ba8b19be6", - ), - "runtime/conversation/conversation.cc": ( - "f87825973603d8c53e8cb63ff12bbe5a8e907821bde4d48f4cbf5bf20f85888c", - "b9a81c34f90ba75846f3beffc6ade99d3e2ae00e832a2793f6b2b086bb756098", - ), - "runtime/conversation/conversation.h": ( - "e86f23bb7c68f79966a581910aa9beda278d581dd74ad5a1c4733195eab2ae89", - "4a2d7b70c0294a789a3190b07eda669bd497c8882e01a47d97b713b2acb2c48d", - ), - "runtime/core/tasks.cc": ( - "bd731f46d33272bbfc0f2ae4a951c7b042db58360403b902e0d08732a993134e", - "05566017ac6af05f6093f4b9f760fc683f6fba461068a612430f1d9011f86c42", - ), - "runtime/engine/io_types.h": ( - "9475b9c9d22c18c93defbbe20d675fdd4a27bf6d9e9b3a2c3130207d7e23dfce", - "87dc1f9846d66e21748adccab0872c1dc4113bc122d58af0446731346b90e34d", - ), -} - - -# v0.19.0 has no terminal cause either; the same change, re-ported. All six -# v0.19.1 preimages equal v0.19.0. -V019_TAGS = frozenset({"v0.19.0", "v0.19.1"}) -V019_PATCH_PATH = "native/bridge/stream_finish_reason_v019.patch" -V019_SOURCES = { - "c/conversation.cc": ( - "a7c772314a0a0b6a0efeb9e0835838b6e94d87c54670728ea4c7cd321a3fe4c8", - "a01a411bdac628d2e90e6bd5a8597a1bc0ba8c6dd0749cd5acb81c82ad547df5", - ), - "c/engine_internal.h": ( - "7955c97b6f1c02a8a7828c370d7ec869dc1f1e23b3fa030b1d075e4a6a495af7", - "e3663bc8be651228f40f6e23cd8ad088bb9975bf85dbc216abf55343157c1ff0", - ), - "runtime/conversation/conversation.cc": ( - "ccfbb9afc6af5306e6176435d040e5358c17058bf063b2d5025d1ef0fa4ff591", - "92e155efa95b5c70bbc78d6f6c099f022056878272166ba41313d7909f924375", - ), - "runtime/conversation/conversation.h": ( - "df2af8ccc041b713b8c1a390c2a9cfab3ab1e97bd4697da15bd78d36cea1fbe4", - "71aaa7ef8227ea675fa39b6a4ddaaed13563e28bebc0c21c36c6ba7355e7486b", - ), - "runtime/core/tasks.cc": ( - "c931b91fa7b81b81c8af01cd2f23562ae43f3cce870b177e174c40a95f45ed4f", - "cbc1d7e16d9dd8d5953a6887d17cde808bf32ed20fcff5c4a69df459720b8915", - ), - "runtime/engine/io_types.h": ( - "aefcaf9df9388b6dede3ba222a1a8c8508479e7e894f3a73eebd14a578294f83", - "c90e7d9a7c307b8f818c351440130e04cb1024d0a77948a5716adac9a053dfdc", - ), -} - - -V020_PATCH_PATH = "native/bridge/stream_finish_reason_v020.patch" -V020_SOURCES = { "c/c_api_internal.h": ( "bcd6bce2a4b986f2cac4ba8869fef944cd3ee2fa47f21f837a1ff5c5876c1504", "546a4e509e368d2d0a3232df4f9c204d9c66beb9fe17fdca089e1ce5a545a777", @@ -101,39 +38,10 @@ } -def patch_path_for(compatibility_tag: str) -> str: - if compatibility_tag == "v0.20.0": - return V020_PATCH_PATH - return V019_PATCH_PATH if compatibility_tag in V019_TAGS else PATCH_PATH - - -def sources_for(compatibility_tag: str) -> dict[str, tuple[str, str]]: - if compatibility_tag == "v0.20.0": - return V020_SOURCES - return V019_SOURCES if compatibility_tag in V019_TAGS else SOURCES - - -def require_finish_reason_patch_decision(compatibility_tag: str) -> bool: - """Returns whether the patch applies; newer sources need a decision. - - Older runtimes keep reporting no finish reason (bridge ABI version 0). - """ - version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", compatibility_tag) - if version and tuple(map(int, version.groups())) < (0, 18, 0): - return False - if compatibility_tag in AUDITED_FINISH_REASON_TAGS: - return True - raise RuntimeError( - f"Stream finish reasons have no explicit decision for " - f"{compatibility_tag}; revalidate the carried patch or record an " - "upstream equivalent in tools/stream_finish_reason_patch.py and " - "docs/upstream_patch_audit.md") - - def finish_reason_patch_manifest(compatibility_tag: str) -> list[dict]: - if not require_finish_reason_patch_decision(compatibility_tag): + if not active_source_carries(compatibility_tag): return [] - patch_path = patch_path_for(compatibility_tag) + patch_path = PATCH_PATH patch_sha256 = hashlib.sha256( (Path(__file__).resolve().parents[1] / patch_path).read_bytes() ).hexdigest() @@ -145,4 +53,4 @@ def finish_reason_patch_manifest(compatibility_tag: str) -> list[dict]: "preimageSha256Lf": preimage, "postimageSha256Lf": postimage, "scope": "source-built runtimes only; excludes official upstream prebuilts", - } for source, (preimage, postimage) in sources_for(compatibility_tag).items()] + } for source, (preimage, postimage) in SOURCES.items()] diff --git a/tools/test_android_gpu_safety.py b/tools/test_android_gpu_safety.py index b753f2b..2808d2f 100644 --- a/tools/test_android_gpu_safety.py +++ b/tools/test_android_gpu_safety.py @@ -6,18 +6,14 @@ import tempfile import unittest -from android_gpu_safety_patch import SOURCES, apply, applies, digest, manifest, sources_for +from android_gpu_safety_patch import SOURCES, apply, digest, manifest ROOT = Path(__file__).resolve().parents[1] class AndroidGpuSafetyTest(unittest.TestCase): def test_version_decision_and_manifest(self): - self.assertFalse(applies("v0.18.1")) - self.assertTrue(applies("v0.19.0")) - with self.assertRaises(RuntimeError): - applies("v0.20.1") - records = manifest("v0.19.0") + records = manifest("v0.20.0") self.assertEqual({r["source"] for r in records}, set(SOURCES)) self.assertEqual(manifest("v0.18.1"), []) @@ -29,7 +25,7 @@ def test_changed_source_refuses_before_patch(self): path.parent.mkdir(parents=True, exist_ok=True) path.write_text("changed upstream\n") with self.assertRaisesRegex(RuntimeError, "requalify"): - apply(root, "v0.19.0") + apply(root, "v0.20.0") def test_policy_and_identity_compile_against_crypto(self): compiler = shutil.which("clang++") or shutil.which("c++") @@ -56,8 +52,8 @@ def test_policy_and_identity_compile_against_crypto(self): "set exact upstream source root to audit patch application") def test_exact_source_patch_and_idempotence(self): source = Path(os.environ["LITERT_GPU_SAFETY_SOURCE"]) - tag = os.environ.get("LITERT_GPU_SAFETY_TAG", "v0.19.0") - sources = sources_for(tag) + tag = os.environ.get("LITERT_GPU_SAFETY_TAG", "v0.20.0") + sources = SOURCES with tempfile.TemporaryDirectory() as temp: root = Path(temp) for name in sources: diff --git a/tools/test_android_protobuf_policy.py b/tools/test_android_protobuf_policy.py index b6661c8..8f669bd 100644 --- a/tools/test_android_protobuf_policy.py +++ b/tools/test_android_protobuf_policy.py @@ -208,9 +208,8 @@ def test_build_entry_points_enforce_policy_before_staging(self): old = self.compile(root / 'old', 'arm64', private=False) private = self.compile(root / 'private', 'arm64') for source_root in (True, False): - for tag, output, rejected in (('v0.19.0', old, True), - ('v0.19.0', private, False), - ('v0.18.0', old, False)): + for tag, output, rejected in (('v0.20.0', old, True), + ('v0.20.0', private, False)): with self.subTest(source_root=source_root, tag=tag, rejected=rejected): args = ['build_upstream_runtime.py', '--upstream-tag', tag, '--platform', 'android', '--arch', 'arm64'] diff --git a/tools/test_asr_litertlm_container_patch.py b/tools/test_asr_litertlm_container_patch.py deleted file mode 100644 index 27d1aa7..0000000 --- a/tools/test_asr_litertlm_container_patch.py +++ /dev/null @@ -1,125 +0,0 @@ -from __future__ import annotations - -import subprocess -import tempfile -import unittest -from pathlib import Path -from unittest.mock import patch - -import build_upstream_runtime as build -from asr_litertlm_container_patch import SOURCES, container_patch_manifest -from asr_overlap_patch import source_sha256 - -REPO = Path(__file__).resolve().parents[1] -FIXTURES = { - "omni/asr/BUILD": "omni_asr_BUILD_v018.txt", - "omni/asr/asr_engine.cc": "asr_engine_v018.cc", - "omni/asr/asr_engine.h": "asr_engine_v018.h", -} - - -def stage_preimage(root: Path) -> None: - for source, fixture in FIXTURES.items(): - path = root / source - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes((REPO / "tools/fixtures" / fixture).read_bytes()) - - -class AsrLitertLmContainerPatchTest(unittest.TestCase): - def test_patch_is_exact_idempotent_and_routes_by_container_metadata(self): - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - stage_preimage(root) - build.patch_asr_litertlm_container(root, "v0.17.1") - for source, (preimage, _) in SOURCES.items(): - self.assertEqual(source_sha256((root / source).read_bytes()), preimage) - - build.patch_asr_litertlm_container(root, "v0.18.0") - for source, (_, postimage) in SOURCES.items(): - self.assertEqual(source_sha256((root / source).read_bytes()), postimage) - engine = (root / "omni/asr/asr_engine.cc").read_text() - self.assertNotIn('absl::EndsWith(config.model_path, ".litertlm");\n if (!use_litert_lm)', engine) - self.assertIn("ResolveDecoderTypeFromLitertLm(*lm_resources, config);", engine) - self.assertIn("AsrMetadata::TF_LITE_ENCODER_DECODER", engine) - self.assertIn("model_resources_(std::move(model_resources))", engine) - - patched = {source: (root / source).read_bytes() for source in SOURCES} - build.patch_asr_litertlm_container(root, "v0.18.0") - for source, data in patched.items(): - self.assertEqual((root / source).read_bytes(), data) - - def test_rejects_drift_without_mutation(self): - for drifted in SOURCES: - with self.subTest(drifted=drifted), tempfile.TemporaryDirectory() as temp: - root = Path(temp) - stage_preimage(root) - path = root / drifted - path.write_bytes(path.read_bytes() + b"# drift\n") - before = {source: (root / source).read_bytes() for source in SOURCES} - with self.assertRaisesRegex(RuntimeError, "requalify .litertlm container patch"): - build.patch_asr_litertlm_container(root, "v0.18.0") - for source, data in before.items(): - self.assertEqual((root / source).read_bytes(), data) - - def test_rejects_partial_postimage_without_mutation(self): - for patched in SOURCES: - with self.subTest(patched=patched), tempfile.TemporaryDirectory() as temp: - complete = Path(temp) / "complete" - stage_preimage(complete) - build.patch_asr_litertlm_container(complete, "v0.18.0") - root = Path(temp) / "partial" - stage_preimage(root) - (root / patched).write_bytes((complete / patched).read_bytes()) - before = {source: (root / source).read_bytes() for source in SOURCES} - with self.assertRaisesRegex(RuntimeError, "requalify .litertlm container patch"): - build.patch_asr_litertlm_container(root, "v0.18.0") - for source, data in before.items(): - self.assertEqual((root / source).read_bytes(), data) - - def test_patch_applies_inside_a_worktree_without_touching_its_root(self): - # Windows builds extract upstream under REPO_ROOT/.tmp, inside a checkout. - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - subprocess.run(["git", "init", "-q", str(root)], check=True) - upstream = root / ".tmp/upstream" - stage_preimage(upstream) - build.patch_asr_litertlm_container(upstream, "v0.18.0") - for source, (_, postimage) in SOURCES.items(): - self.assertEqual(source_sha256((upstream / source).read_bytes()), postimage) - self.assertFalse((root / "omni").exists()) - - def test_postimage_verification_rejects_incorrect_apply(self): - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - stage_preimage(root) - with patch.object(build.subprocess, "run"): - with self.assertRaisesRegex(RuntimeError, "postimage mismatch"): - build.patch_asr_litertlm_container(root, "v0.18.0") - - def test_newer_and_unknown_versions_require_explicit_decision(self): - for tag in ("v0.18.2", "v0.19.2", "main"): - with self.subTest(tag=tag): - for gate in (lambda: build.patch_asr_litertlm_container(Path("missing"), tag), - lambda: container_patch_manifest(tag)): - with self.assertRaisesRegex(RuntimeError, "no explicit decision.*" + tag): - gate() - - def test_runtime_applies_container_patch_before_bazel(self): - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - with (patch.object(build, "patch_asr_untimed_overlap"), - patch.object(build, "patch_asr_litertlm_container", - side_effect=RuntimeError("container gate")) as gate): - with self.assertRaisesRegex(RuntimeError, "container gate"): - build.build_runtime(root, "macos", "arm64", "v0.18.0", "2") - gate.assert_called_once_with(root, "v0.18.0") - - def test_manifest_records_every_patched_source(self): - records = container_patch_manifest("v0.18.0") - self.assertEqual([record["source"] for record in records], list(SOURCES)) - self.assertEqual({record["id"] for record in records}, {"asr-litertlm-container"}) - self.assertEqual(container_patch_manifest("v0.17.1"), []) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_asr_untimed_overlap.py b/tools/test_asr_untimed_overlap.py index 607a6da..e3453de 100644 --- a/tools/test_asr_untimed_overlap.py +++ b/tools/test_asr_untimed_overlap.py @@ -27,7 +27,7 @@ def probe(command, **kwargs): def test_newer_and_unknown_versions_require_explicit_patch_decision(self): from asr_overlap_patch import source_patch_manifest - for tag in ("v0.18.2", "v0.19.2", "v1.0.0", "v0.19.0-rc.1", "main"): + for tag in ("v0.20.1", "v0.20.2", "v1.0.0", "v0.19.0-rc.1", "main"): with self.subTest(tag=tag): # Check before source I/O or build, and on the release manifest # path too. Updating a postimage hash cannot bypass this gate. @@ -49,84 +49,85 @@ def test_fast_evaluation_distance_matches_reference(self): def test_patch_is_exact_idempotent_and_rejects_drift(self): with tempfile.TemporaryDirectory() as temp: root = Path(temp) - source = root / "omni/asr/timestamp_text_merger.cc" + source = root / "omni/speech2text/timestamp_text_merger.cc" source.parent.mkdir(parents=True) - original = (REPO / "tools/fixtures/timestamp_text_merger_v018.cc").read_bytes() + original = (REPO / "tools/fixtures/timestamp_text_merger_v020.cc").read_bytes() source.write_bytes(original) build.patch_asr_untimed_overlap(root, "v0.17.1") self.assertEqual(source.read_bytes(), original) - build.patch_asr_untimed_overlap(root, "v0.18.0") + build.patch_asr_untimed_overlap(root, "v0.20.0") patched = source.read_bytes() self.assertNotEqual(patched, original) - build.patch_asr_untimed_overlap(root, "v0.18.0") + build.patch_asr_untimed_overlap(root, "v0.20.0") self.assertEqual(source.read_bytes(), patched) source.write_bytes(original + b"// drift\n") with self.assertRaisesRegex(RuntimeError, "requalify untimed overlap"): - build.patch_asr_untimed_overlap(root, "v0.18.0") + build.patch_asr_untimed_overlap(root, "v0.20.0") self.assertEqual(source.read_bytes(), original + b"// drift\n") def test_crlf_and_autocrlf_application_and_postimage(self): # Extends the audit crlf.sh/crlf2.sh matrix: patch bytes stay LF; # pre/post image hashes compare normalized source, even on Windows. from asr_overlap_patch import POSTIMAGE_SHA256, source_sha256 - original = (REPO / "tools/fixtures/timestamp_text_merger_v018.cc").read_bytes() + original = (REPO / "tools/fixtures/timestamp_text_merger_v020.cc").read_bytes() for autocrlf in ("true", "false"): for ending in (b"\n", b"\r\n"): with self.subTest(autocrlf=autocrlf, ending=ending), tempfile.TemporaryDirectory() as temp: root = Path(temp) config = root / "gitconfig" config.write_text(f"[core]\n autocrlf = {autocrlf}\n") - source = root / "omni/asr/timestamp_text_merger.cc" + source = root / "omni/speech2text/timestamp_text_merger.cc" source.parent.mkdir(parents=True) source.write_bytes(original.replace(b"\n", ending)) with patch.dict(os.environ, {"GIT_CONFIG_GLOBAL": str(config)}): - build.patch_asr_untimed_overlap(root, "v0.18.0") + build.patch_asr_untimed_overlap(root, "v0.20.0") self.assertEqual(source_sha256(source.read_bytes()), POSTIMAGE_SHA256) - build.patch_asr_untimed_overlap(root, "v0.18.0") + build.patch_asr_untimed_overlap(root, "v0.20.0") def test_patch_attributes_preserve_lf_on_windows_checkout(self): with tempfile.TemporaryDirectory() as temp: root = Path(temp) subprocess.run(["git", "init", "-q", str(root)], check=True) - for name in (".gitattributes", "native/bridge/asr_untimed_overlap.patch"): + for name in (".gitattributes", "native/bridge/asr_untimed_overlap_v019.patch"): dest = root / name dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes((REPO / name).read_bytes()) subprocess.run(["git", "-c", "core.autocrlf=true", "add", "."], cwd=root, check=True) - target = root / "native/bridge/asr_untimed_overlap.patch" + target = root / "native/bridge/asr_untimed_overlap_v019.patch" target.unlink() subprocess.run(["git", "-c", "core.autocrlf=true", "checkout-index", "-a"], cwd=root, check=True) - self.assertEqual(target.read_bytes(), (REPO / "native/bridge/asr_untimed_overlap.patch").read_bytes()) + self.assertEqual(target.read_bytes(), (REPO / "native/bridge/asr_untimed_overlap_v019.patch").read_bytes()) self.assertNotIn(b"\r", target.read_bytes()) def test_postimage_verification_rejects_incorrect_apply(self): with tempfile.TemporaryDirectory() as temp: root = Path(temp) - source = root / "omni/asr/timestamp_text_merger.cc" + source = root / "omni/speech2text/timestamp_text_merger.cc" source.parent.mkdir(parents=True) - source.write_bytes((REPO / "tools/fixtures/timestamp_text_merger_v018.cc").read_bytes()) + source.write_bytes((REPO / "tools/fixtures/timestamp_text_merger_v020.cc").read_bytes()) with patch.object(build.subprocess, "run"): with self.assertRaisesRegex(RuntimeError, "postimage mismatch"): - build.patch_asr_untimed_overlap(root, "v0.18.0") + build.patch_asr_untimed_overlap(root, "v0.20.0") def test_runtime_patches_before_bazel_including_source_root_mode(self): with tempfile.TemporaryDirectory() as temp: root = Path(temp) - with patch.object(build, "patch_asr_untimed_overlap", side_effect=RuntimeError("patch gate")) as gate: + with (patch.object(build, "verify_carried_dependency_pins"), + patch.object(build, "patch_asr_untimed_overlap", side_effect=RuntimeError("patch gate")) as gate): with self.assertRaisesRegex(RuntimeError, "patch gate"): - build.build_runtime(root, "macos", "arm64", "v0.18.0", "2") - gate.assert_called_once_with(root, "v0.18.0") + build.build_runtime(root, "macos", "arm64", "v0.20.0", "2") + gate.assert_called_once_with(root, "v0.20.0") def test_patch_applies_inside_a_worktree_without_touching_its_root(self): with tempfile.TemporaryDirectory() as temp: root = Path(temp) subprocess.run(["git", "init", "-q", str(root)], check=True) upstream = root / ".tmp/upstream" - source = upstream / "omni/asr/timestamp_text_merger.cc" + source = upstream / "omni/speech2text/timestamp_text_merger.cc" source.parent.mkdir(parents=True) - original = (REPO / "tools/fixtures/timestamp_text_merger_v018.cc").read_bytes() + original = (REPO / "tools/fixtures/timestamp_text_merger_v020.cc").read_bytes() source.write_bytes(original) - build.patch_asr_untimed_overlap(upstream, "v0.18.0") + build.patch_asr_untimed_overlap(upstream, "v0.20.0") self.assertNotEqual(source.read_bytes(), original) self.assertFalse((root / "omni").exists()) diff --git a/tools/test_build_upstream_runtime.py b/tools/test_build_upstream_runtime.py index 4d795fc..825b3d8 100644 --- a/tools/test_build_upstream_runtime.py +++ b/tools/test_build_upstream_runtime.py @@ -16,10 +16,6 @@ import build_upstream_runtime import package_upstream_prebuilts from bazel_repository_provenance import HTTP_ARCHIVE, UPSTREAM_REGISTRY -from litert_cpu_options_identifier_patch import ( - LITERT_ARCHIVE_SHA256 as CPU_OPTIONS_SHA256, - LITERT_REF as CPU_OPTIONS_REF, -) from litert_lm_symbols import ANDROID_OPENCL_SAMPLER_SYMBOLS, ANDROID_WEBGPU_SAMPLER_SYMBOLS from litert_stage_spatial_tensors_patch import ( LITERT_ARCHIVE_SHA256, @@ -29,10 +25,9 @@ from test_runtime_dependency_utils import write_elf_with_exports from xnnpack_pf32_sme2_patch import ( TENSORFLOW_ARCHIVE, - V019_TENSORFLOW_REF, - V019_XNNPACK_COMMIT, - V019_XNNPACK_SHA256, - V020_TENSORFLOW_REF, + TENSORFLOW_REF, + XNNPACK_COMMIT, + XNNPACK_SHA256, declare_patched_xnnpack, ) @@ -51,175 +46,23 @@ def litert_workspace(ref: str, digest: str) -> str: class BuildUpstreamRuntimeTest(unittest.TestCase): - def test_ios_framework_patch_applies_to_old_and_current_litert(self) -> None: - patch_file = ( - build_upstream_runtime.REPO_ROOT - / "native/bridge/litert_ios_framework_paths.patch" - ) - for version in ("17", "18"): - with self.subTest(version=version), tempfile.TemporaryDirectory() as temp: - root = Path(temp) - target = root / "litert/runtime/accelerators/gpu_registry.cc" - target.parent.mkdir(parents=True) - original = ( - Path(__file__).parent - / f"fixtures/litert_v0_{version}_gpu_registry_excerpt.cc" - ).read_text() - target.write_text(original) - subprocess.run( - ["git", "apply", "--unidiff-zero", "--check", str(patch_file)], - cwd=root, - check=True, - capture_output=True, - ) - subprocess.run( - ["git", "apply", "--unidiff-zero", str(patch_file)], - cwd=root, - check=True, - capture_output=True, - ) - patched = target.read_text() - self.assertIn( - '"@executable_path/Frameworks/LiteRtMetalAccelerator.framework/"', - patched, - ) - self.assertNotIn('"libLiteRtMetalAccelerator" SO_EXT', patched) - self.assertIn('"libLiteRtWebGpuAccelerator" SO_EXT', patched) - if version == "18": - self.assertIn("// Inside an Apple framework bundle", patched) - self.assertEqual(patched.count('"LiteRtMetalAccelerator",'), 2) - # Unknown iOS layouts must still fail instead of silently dropping the path fix. - target.write_text( - original.replace("#elif TARGET_OS_IPHONE", "#elif CHANGED_PLATFORM") - ) - result = subprocess.run( - ["git", "apply", "--unidiff-zero", "--check", str(patch_file)], - cwd=root, - capture_output=True, - ) - self.assertNotEqual(result.returncode, 0) - - def test_sentencepiece_patch_delimits_each_file_for_bazel(self) -> None: - lines = (Path(__file__).resolve().parents[1] / "native/bridge/sentencepiece_bpe_null.patch").read_text().splitlines() - files = [] - for index, line in enumerate(lines): - if line.startswith("--- a/"): - name = line.removeprefix("--- a/") - self.assertEqual(lines[index - 1], f"diff --git a/{name} b/{name}") - files.append(name) - self.assertEqual(set(files), {"src/bpe_model.cc", "src/model_interface.cc", "src/model_interface.h"}) - - def test_download_wires_bpe_compatibility_only_for_v017_and_later(self) -> None: - affected = 'LITERT_REF = "9fe5be45564c868408e6514c8aabb83e211a0911"\n' - for tag, workspace, enabled in [("v0.16.0", "", False), ("v0.17.0", affected, True), ("v0.17.1", affected, True)]: - with self.subTest(tag=tag), tempfile.TemporaryDirectory() as temp: - root = Path(temp) - source = root / "source" - source.mkdir() - (source / "WORKSPACE").write_text(workspace, encoding="utf-8") - with patch.object(build_upstream_runtime, "download_to_path"), \ - patch.object(build_upstream_runtime.tarfile, "open"), \ - patch.object(build_upstream_runtime, "patch_upstream_workspace") as apply: - self.assertEqual(build_upstream_runtime.download_upstream(tag, tag, root), source) - self.assertEqual(apply.call_args.kwargs["patch_bpe_null_piece"], enabled) - self.assertEqual(apply.call_args.kwargs["patch_gpu_environment_teardown"], enabled) - - def test_workspace_applies_bpe_patch_and_preserves_file_on_rejection(self) -> None: - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - path = root / "WORKSPACE" - text = ('http_archive(\n name = "minizip",\n' - f' url = "{build_upstream_runtime.ZLIB_URL}",\n)\n' - 'http_archive(\n name = "sentencepiece",\n' - ' sha256 = "92381f713e094a15a1ccff1ac4a5315a4c4b82a99ac1332d6ac53c9dc8e1bcf1",\n' - ' strip_prefix = "sentencepiece-0.2.2",\n' - ' url = "https://github.com/google/sentencepiece/archive/refs/tags/v0.2.2.tar.gz",\n)') - path.write_text(text) - build_upstream_runtime.patch_upstream_workspace(root, patch_ios_framework_paths=False, patch_bpe_null_piece=True) - self.assertIn('patches = ["@//bridge:sentencepiece_bpe_null.patch"]', path.read_text()) - invalid = text.replace('92381f', '000000') - path.write_text(invalid) - with self.assertRaisesRegex(RuntimeError, "source changed"): - build_upstream_runtime.patch_upstream_workspace(root, patch_ios_framework_paths=False, patch_bpe_null_piece=True) - self.assertEqual(path.read_text(), invalid) - - def test_sentencepiece_patch_is_exact_source_and_idempotent(self) -> None: - block = ('http_archive(\n name = "sentencepiece",\n' - ' sha256 = "92381f713e094a15a1ccff1ac4a5315a4c4b82a99ac1332d6ac53c9dc8e1bcf1",\n' - ' strip_prefix = "sentencepiece-0.2.2",\n' - ' url = "https://github.com/google/sentencepiece/archive/refs/tags/v0.2.2.tar.gz",\n)') - patched = build_upstream_runtime.patch_sentencepiece_bpe_null(block) - self.assertIn('patches = ["@//bridge:sentencepiece_bpe_null.patch"]', patched) - self.assertEqual(build_upstream_runtime.patch_sentencepiece_bpe_null(patched), patched) - for invalid in (block.replace('92381f', '000000'), - block.replace('0.2.2', '0.2.3'), - block + '\n' + block, - block.replace(' sha256', ' patches = ["other.patch"],\n sha256')): - with self.subTest(invalid=invalid), self.assertRaises(RuntimeError): - build_upstream_runtime.patch_sentencepiece_bpe_null(invalid) - - def test_runtime_selects_capabilities_owner_by_upstream_version(self) -> None: - for tag, expected in [("v0.16.0", False), ("v0.17.0", True), ("v0.17.1", True)]: - with self.subTest(tag=tag), tempfile.TemporaryDirectory() as temp: - root = Path(temp) - with patch.object(build_upstream_runtime, "materialize_git_lfs_libraries", return_value=0), \ - patch.object(build_upstream_runtime, "bazel_command", return_value=["bazel"]), \ - patch.object(build_upstream_runtime, "run", side_effect=RuntimeError("captured build")) as run: - with self.assertRaisesRegex(RuntimeError, "captured build"): - build_upstream_runtime.build_runtime(root, "macos", "arm64", tag, "3") - command = run.call_args.args[0] - self.assertEqual("--define=litert_lm_capabilities_in_c_engine=true" in command, expected) - - def test_desktop_build_selects_shared_runtime_only_for_v016_to_v018(self) -> None: - for platform, arch in build_upstream_runtime.RUNTIME_TARGETS: - for tag in ("v0.15.0", "v0.16.0", "v0.17.0", "v0.17.1", "v0.18.1", "v0.19.0", "v0.19.1"): - with self.subTest(platform=platform, arch=arch, tag=tag), tempfile.TemporaryDirectory() as temp: - root = Path(temp) - gate = root / "runtime/conversation/model_data_processor/BUILD" - gate.parent.mkdir(parents=True) - gate.write_bytes((Path(__file__).parent / "fixtures/ios_fst_gate.BUILD").read_bytes()) - with patch.object(build_upstream_runtime, "materialize_git_lfs_libraries", return_value=0), \ - patch.object(build_upstream_runtime, "patch_upstream_ios_sampler_path"), \ - patch.object(build_upstream_runtime, "patch_asr_untimed_overlap"), \ - patch.object(build_upstream_runtime, "patch_asr_litertlm_container"), \ - patch.object(build_upstream_runtime, "patch_stream_finish_reason"), \ - patch.object(build_upstream_runtime, "patch_huggingface_token_bytes"), \ - patch.object(build_upstream_runtime, "patch_step_zero_state") as apply_state, \ - patch.object(build_upstream_runtime, "verify_carried_dependency_pins"), \ - patch.object(build_upstream_runtime, "fetch_audited_archives"), \ - patch.object(build_upstream_runtime, "apply_android_gpu_safety"), \ - patch.object(build_upstream_runtime, "verify_dynamic_runtime"), \ - patch.object(build_upstream_runtime, "bazel_command", return_value=["bazel"]), \ - patch.object(build_upstream_runtime, "run", side_effect=RuntimeError("captured build")) as run: - with self.assertRaisesRegex(RuntimeError, "captured build"): - build_upstream_runtime.build_runtime(root, platform, arch, tag, "3") - apply_state.assert_called_once_with(root, tag) - command = run.call_args.args[0] - self.assertEqual("--define=LITERT_LM_FST_CONSTRAINTS_DISABLED=1" in command, platform == "ios" and tag not in {"v0.15.0", "v0.16.0"}) - dynamic = platform in {"linux", "windows"} and tag not in {"v0.15.0", "v0.19.0", "v0.19.1"} - self.assertEqual("--define=litert_runtime_link_mode=dynamic" in command, dynamic) - self.assertEqual("--define=litert_link_capi_so=true" in command, not dynamic) - self.assertEqual("--define=litert_lm_in_process_litert=true" in command, - tag in {"v0.19.0", "v0.19.1"}) - self.assertIn("--define=resolve_symbols_in_exec=false", command) - self.assertIn("--nohome_rc", command) - self.assertIn("--nosystem_rc", command) - self.assertEqual("--noenable_bzlmod" in command, - tag in {"v0.18.1", "v0.19.0", "v0.19.1"}) - self.assertEqual("--define=litert_lm_android_webgpu_sampler=true" in command, - platform == "android" and tag in {"v0.19.0", "v0.19.1"}) + def test_source_build_rejects_an_older_compatibility_tag(self) -> None: + with self.assertRaisesRegex(RuntimeError, "historical native release ref"): + build_upstream_runtime.build_runtime(Path("missing"), "macos", "arm64", "v0.19.1", None) - def test_android_webgpu_sampler_define_links_the_static_sampler(self) -> None: + def test_android_build_links_the_opencl_sampler_with_combined_gpu(self) -> None: bazel = (build_upstream_runtime.REPO_ROOT / "native/bridge/BUILD.bazel").read_text() setting = re.search( - r'name = "android_webgpu_sampler",\s*constraint_values = \["@platforms//os:android"\],' + r'name = "android_opencl_sampler",\s*constraint_values = \["@platforms//os:android"\],' r'\s*define_values = \{"([^"]+)": "true"\}', bazel) self.assertIsNotNone(setting) script = Path(build_upstream_runtime.__file__).read_text() self.assertIn(f'"--define={setting.group(1)}=true"', script) - self.assertEqual(len(re.findall( - r'":android_webgpu_sampler": \["//runtime/components:top_k_webgpu_sampler_static"\]', - bazel)), 1) + self.assertIn('"--//runtime/executor:gpu_accelerator=webgpu"', script) + self.assertIn( + '":android_opencl_sampler": ["//runtime/components:top_k_opencl_sampler_static"]', + bazel, + ) def test_android_v019_build_rejects_a_runtime_without_both_gpu_samplers(self) -> None: both = ANDROID_OPENCL_SAMPLER_SYMBOLS + ANDROID_WEBGPU_SAMPLER_SYMBOLS @@ -273,7 +116,7 @@ def test_v019_runtime_must_not_import_shared_litert(self) -> None: def test_main_rejects_shared_litert_on_both_build_paths(self) -> None: for source_root in (True, False): with self.subTest(source_root=source_root), tempfile.TemporaryDirectory() as temp: - argv = ["build_upstream_runtime.py", "--upstream-tag", "v0.19.1", + argv = ["build_upstream_runtime.py", "--upstream-tag", "v0.20.0", "--platform", "linux", "--arch", "x64"] if source_root: argv += ["--source-root", temp] @@ -331,12 +174,12 @@ def test_workspace_accepts_upstream_v017_zlib_mirrors(self) -> None: f' "{build_upstream_runtime.ZLIB_URL}",\n ],\n)\n') workspace.write_text(text) build_upstream_runtime.patch_upstream_workspace( - root, patch_ios_framework_paths=False) + root) self.assertEqual(workspace.read_text(), text) workspace.write_text(text.replace(build_upstream_runtime.ZLIB_URL, "https://invalid.example/zlib")) with self.assertRaisesRegex(RuntimeError, "Expected zlib URL"): build_upstream_runtime.patch_upstream_workspace( - root, patch_ios_framework_paths=False) + root) def test_source_archive_filename_never_contains_the_raw_ref_path(self) -> None: with tempfile.TemporaryDirectory() as temp: @@ -377,7 +220,7 @@ def test_workspace_applies_spatial_staging_only_to_the_audited_pin(self) -> None def test_windows_v020_uses_the_android_rules_and_engine_fd_patches(self) -> None: call = "tf_workspace2()\n" original = ( - f'TENSORFLOW_REF = "{V020_TENSORFLOW_REF}"\n' + f'TENSORFLOW_REF = "{TENSORFLOW_REF}"\n' 'load("@org_tensorflow//tensorflow:workspace2.bzl", "tf_workspace2")\n\n' + call ) @@ -387,7 +230,6 @@ def test_windows_v020_uses_the_android_rules_and_engine_fd_patches(self) -> None patch_asr_untimed_overlap=DEFAULT, patch_stream_finish_reason=DEFAULT, patch_huggingface_token_bytes=DEFAULT, - patch_step_zero_state=DEFAULT, apply_android_gpu_safety=DEFAULT, patch_windows_engine_fd=DEFAULT, materialize_git_lfs_libraries=DEFAULT, @@ -403,8 +245,7 @@ def test_windows_v020_uses_the_android_rules_and_engine_fd_patches(self) -> None calls["materialize_git_lfs_libraries"].return_value = 0 calls["prepare_bridge_package"].return_value = [] calls["run"].side_effect = RuntimeError("Bazel reached") - for platform, tag in (("windows", "v0.20.0"), ("linux", "v0.20.0"), - ("windows", "v0.19.1")): + for platform, tag in (("windows", "v0.20.0"), ("linux", "v0.20.0")): with self.subTest(platform=platform, tag=tag): workspace.write_text(original, encoding="utf-8") fd_patch.reset_mock() @@ -428,7 +269,7 @@ def test_windows_v020_uses_the_android_rules_and_engine_fd_patches(self) -> None def test_source_root_verifies_resolved_archives_before_compilation(self) -> None: workspace = litert_workspace(LITERT_REF, LITERT_ARCHIVE_SHA256) + declare_patched_xnnpack( - f'TENSORFLOW_REF = "{V019_TENSORFLOW_REF}"\n' + TENSORFLOW_ARCHIVE + ")\n" + f'TENSORFLOW_REF = "{TENSORFLOW_REF}"\n' + TENSORFLOW_ARCHIVE + ")\n" ) tree_hash = ( @@ -450,7 +291,7 @@ def resolved_archive(name: str, digest: str, prefix: str, } litert = resolved_archive("litert", LITERT_ARCHIVE_SHA256, f"LiteRT-{LITERT_REF}") - xnnpack = resolved_archive("XNNPACK", V019_XNNPACK_SHA256, f"XNNPACK-{V019_XNNPACK_COMMIT}") + xnnpack = resolved_archive("XNNPACK", XNNPACK_SHA256, f"XNNPACK-{XNNPACK_COMMIT}") wrong = resolved_archive("litert", "0" * 64, f"LiteRT-{LITERT_REF}") wrong_tree = resolved_archive("litert", LITERT_ARCHIVE_SHA256, f"LiteRT-{LITERT_REF}", "f" * 64) local = {**litert, "original_rule_class": "local_repository"} @@ -479,7 +320,6 @@ def resolved_archive(name: str, digest: str, prefix: str, patch_asr_untimed_overlap=DEFAULT, patch_stream_finish_reason=DEFAULT, patch_huggingface_token_bytes=DEFAULT, - patch_step_zero_state=DEFAULT, apply_android_gpu_safety=DEFAULT, materialize_git_lfs_libraries=DEFAULT, run=DEFAULT, @@ -585,7 +425,7 @@ def run(command, cwd, *, capture_output=False): calls["run"].side_effect = run args = ["build_upstream_runtime.py", "--source-root", str(root), - "--upstream-tag", "v0.19.1", "--platform", "macos", "--arch", "arm64"] + "--upstream-tag", "v0.20.0", "--platform", "macos", "--arch", "arm64"] with patch("sys.argv", args), self.assertRaisesRegex(RuntimeError, message) as failure: build_upstream_runtime.main() compilations = [call for call in calls["run"].call_args_list if "build" in call.args[0]] @@ -599,7 +439,7 @@ def run(command, cwd, *, capture_output=False): def test_source_root_rejects_workspace_rc_repository_overrides_before_bazel(self) -> None: workspace = litert_workspace(LITERT_REF, LITERT_ARCHIVE_SHA256) + declare_patched_xnnpack( - f'TENSORFLOW_REF = "{V019_TENSORFLOW_REF}"\n' + TENSORFLOW_ARCHIVE + ")\n" + f'TENSORFLOW_REF = "{TENSORFLOW_REF}"\n' + TENSORFLOW_ARCHIVE + ")\n" ) fixtures = ( ("build --override_repository=litert=alternate_repo", "override_repository"), @@ -610,14 +450,13 @@ def test_source_root_rejects_workspace_rc_repository_overrides_before_bazel(self root = Path(temp) (root / "WORKSPACE").write_text(workspace, encoding="utf-8") args = ["build_upstream_runtime.py", "--source-root", str(root), - "--upstream-tag", "v0.19.1", "--platform", "macos", "--arch", "arm64"] + "--upstream-tag", "v0.20.0", "--platform", "macos", "--arch", "arm64"] for fixture, option in fixtures: with self.subTest(fixture=fixture), patch("sys.argv", args), patch.multiple( build_upstream_runtime, patch_asr_untimed_overlap=DEFAULT, patch_stream_finish_reason=DEFAULT, patch_huggingface_token_bytes=DEFAULT, - patch_step_zero_state=DEFAULT, apply_android_gpu_safety=DEFAULT, materialize_git_lfs_libraries=DEFAULT, run=DEFAULT, @@ -631,7 +470,7 @@ def test_source_root_rejects_workspace_rc_repository_overrides_before_bazel(self def test_build_routes_reject_identical_workspace_files_before_patching(self) -> None: workspace = litert_workspace(LITERT_REF, LITERT_ARCHIVE_SHA256) + declare_patched_xnnpack( - f'TENSORFLOW_REF = "{V019_TENSORFLOW_REF}"\n' + TENSORFLOW_ARCHIVE + ")\n" + f'TENSORFLOW_REF = "{TENSORFLOW_REF}"\n' + TENSORFLOW_ARCHIVE + ")\n" ) with tempfile.TemporaryDirectory() as temp: work_dir = Path(temp) @@ -642,7 +481,7 @@ def test_build_routes_reject_identical_workspace_files_before_patching(self) -> message = "both WORKSPACE and WORKSPACE.bazel" args = ["build_upstream_runtime.py", "--source-root", str(root), - "--upstream-tag", "v0.19.1", "--platform", "macos", "--arch", "arm64"] + "--upstream-tag", "v0.20.0", "--platform", "macos", "--arch", "arm64"] with self.subTest(route="prepared"), patch("sys.argv", args), patch.object( build_upstream_runtime, "patch_asr_untimed_overlap", side_effect=RuntimeError("reached source patching"), @@ -655,16 +494,16 @@ def test_build_routes_reject_identical_workspace_files_before_patching(self) -> with self.subTest(route="archive"), patch.object( build_upstream_runtime, "download_to_path", ), patch.object(build_upstream_runtime.tarfile, "open"), patch.object( - build_upstream_runtime, "patch_workspace_build", + build_upstream_runtime, "patch_upstream_workspace", side_effect=RuntimeError("reached workspace patching"), ) as patch_workspace: with self.assertRaisesRegex(RuntimeError, message): - build_upstream_runtime.download_upstream("v0.19.1", "v0.19.1", work_dir) + build_upstream_runtime.download_upstream("v0.20.0", "v0.20.0", work_dir) patch_workspace.assert_not_called() with self.subTest(route="verifier"), self.assertRaisesRegex(RuntimeError, message): build_upstream_runtime.verify_carried_dependency_pins( - root, "v0.19.1", spatial_staging=True, cpu_options=False, xnnpack=True, + root, "v0.20.0", ) for name in ("WORKSPACE", "WORKSPACE.bazel"): @@ -678,33 +517,28 @@ def test_source_root_rejects_dependency_archive_drift_before_bazel(self) -> None f' name = "litert",\n patches = ["@//bridge:{Path(STAGING_PATCH).name}"],\n', ) xnnpack = declare_patched_xnnpack( - f'TENSORFLOW_REF = "{V019_TENSORFLOW_REF}"\n' + TENSORFLOW_ARCHIVE + ")\n" + f'TENSORFLOW_REF = "{TENSORFLOW_REF}"\n' + TENSORFLOW_ARCHIVE + ")\n" ) cases = ( - ("alternate LiteRT archive", "v0.19.1", litert.replace(LITERT_REF, parent_ref) + ("alternate LiteRT archive", "v0.20.0", litert.replace(LITERT_REF, parent_ref) .replace(LITERT_ARCHIVE_SHA256, parent_sha) + xnnpack, "Unexpected LITERT_REF"), - ("changed LiteRT digest", "v0.19.1", + ("changed LiteRT digest", "v0.20.0", litert.replace(LITERT_ARCHIVE_SHA256, parent_sha) + xnnpack, "Unexpected LITERT_SHA256"), - ("archive overrides digest", "v0.19.1", + ("archive overrides digest", "v0.20.0", litert.replace("sha256 = LITERT_SHA256,", f'sha256 = "{parent_sha}",') + xnnpack, "Unexpected LiteRT archive sha256"), - ("shadowed LiteRT revision", "v0.19.1", + ("shadowed LiteRT revision", "v0.20.0", f'LITERT_REF="{parent_ref}"\n' + litert + xnnpack, "Unexpected LITERT_REF"), - ("CPU options LiteRT pin drift", "v0.18.1", - litert_workspace(CPU_OPTIONS_REF, CPU_OPTIONS_SHA256).replace(CPU_OPTIONS_REF, LITERT_REF), - "Unexpected LITERT_REF for LiteRT CPU options"), - ("XNNPACK digest drift", "v0.19.1", - litert + xnnpack.replace(V019_XNNPACK_SHA256, "0" * 64), "Unexpected XNNPACK archive"), - ("XNNPACK archive missing", "v0.19.0", litert, "Unexpected XNNPACK archive"), + ("XNNPACK digest drift", "v0.20.0", + litert + xnnpack.replace(XNNPACK_SHA256, "0" * 64), "Unexpected XNNPACK archive"), + ("XNNPACK archive missing", "v0.20.0", litert, "Unexpected XNNPACK archive"), ) for label, tag, workspace, message in cases: with self.subTest(label=label), tempfile.TemporaryDirectory() as temp, patch.multiple( build_upstream_runtime, patch_asr_untimed_overlap=DEFAULT, - patch_asr_litertlm_container=DEFAULT, patch_stream_finish_reason=DEFAULT, patch_huggingface_token_bytes=DEFAULT, - patch_step_zero_state=DEFAULT, apply_android_gpu_safety=DEFAULT, materialize_git_lfs_libraries=DEFAULT, run=DEFAULT, @@ -718,7 +552,6 @@ def test_source_root_rejects_dependency_archive_drift_before_bazel(self) -> None with patch("sys.argv", args), self.assertRaisesRegex(RuntimeError, message): build_upstream_runtime.main() calls["run"].assert_not_called() - calls["patch_step_zero_state"].assert_not_called() def test_spatial_staging_postimages_fail_on_drift_or_missing_files(self) -> None: with tempfile.TemporaryDirectory() as temp: @@ -730,7 +563,7 @@ def test_spatial_staging_postimages_fail_on_drift_or_missing_files(self) -> None (source_root / "bazel-out").symlink_to(exec_root / "bazel-out", target_is_directory=True) sources = {} files = [] - for name in build_upstream_runtime.stage_spatial_tensors_identity("v0.19.1")[3]: + for name in build_upstream_runtime.STAGING_SOURCES: postimage = name.encode() + b"\n" sources[name] = ("", build_upstream_runtime.source_sha256(postimage)) file = output_base / "external" / "litert" / name @@ -738,8 +571,7 @@ def test_spatial_staging_postimages_fail_on_drift_or_missing_files(self) -> None file.write_bytes(postimage.replace(b"\n", b"\r\n")) files.append(file) - with patch.object(build_upstream_runtime, "stage_spatial_tensors_identity", - return_value=("", "", "", sources)): + with patch.object(build_upstream_runtime, "STAGING_SOURCES", sources): build_upstream_runtime.verify_stage_spatial_tensors_postimages(source_root) for file in files: with self.subTest(file=file.name): @@ -752,189 +584,6 @@ def test_spatial_staging_postimages_fail_on_drift_or_missing_files(self) -> None build_upstream_runtime.verify_stage_spatial_tensors_postimages(source_root) file.write_bytes(original) - def test_workspace_adds_litert_apple_framework_patch(self) -> None: - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - workspace = root / "WORKSPACE" - workspace.write_text( - "\n".join( - [ - "http_archive(", - ' name = "minizip",', - f' url = "{build_upstream_runtime.ZLIB_URL}",', - ")", - "http_archive(", - ' name = "litert",', - ")", - ] - ), - encoding="utf-8", - ) - - build_upstream_runtime.patch_upstream_workspace(root) - build_upstream_runtime.patch_upstream_workspace(root) - - patched = workspace.read_text(encoding="utf-8") - self.assertEqual( - patched.count("litert_ios_framework_paths.patch"), - 1, - ) - self.assertIn( - build_upstream_runtime.ZLIB_GITHUB_MIRROR_URL, - patched, - ) - - def test_workspace_adds_gpu_environment_teardown_patch_for_v017(self) -> None: - needs = build_upstream_runtime.needs_gpu_environment_teardown_patch - affected = 'LITERT_REF = "9fe5be45564c868408e6514c8aabb83e211a0911"\n' - reordered = 'LITERT_REF = "86112a3263efdbcf2183c48580c9aa1b89850c98"\n' - self.assertTrue(needs(affected, "v0.17.0")) - self.assertTrue(needs(affected, "v0.17.1")) - # A development build keeps the stable compatibility tag. - self.assertFalse(needs(reordered, "v0.17.1")) - for ref, tag in [ - ("3cb830ad9c94f9922f0a88dd431b005413628919", "v0.15.0"), - ("0ff28117f1cb5556d0e015bf80b773f74e2bee51", "v0.16.1"), - ("761d99cb90e20c67efcb3fe1119a60c92381bd1a", "v0.17.0"), - ]: - self.assertTrue(needs(f'LITERT_REF = "{ref}"\n', tag), ref) - self.assertFalse(needs("", "v0.16.1")) - with self.assertRaisesRegex(RuntimeError, "LITERT_REF"): - needs("", "v0.17.0") - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - workspace = root / "WORKSPACE" - workspace.write_text( - f'http_archive(\n name = "minizip",\n url = "{build_upstream_runtime.ZLIB_URL}",\n)\n' - 'http_archive(\n name = "litert",\n)\n', - encoding="utf-8", - ) - - for _ in range(2): - build_upstream_runtime.patch_upstream_workspace( - root, patch_gpu_environment_teardown=True) - - patched = workspace.read_text(encoding="utf-8") - self.assertEqual( - patched.count( - ' patches = ["@//bridge:litert_ios_framework_paths.patch", ' - '"@//bridge:litert_gpu_environment_destroy_callback.patch"],\n' - ), - 1, - ) - with self.assertRaisesRegex(RuntimeError, "Unexpected LiteRT patches"): - build_upstream_runtime.patch_upstream_workspace(root) - - def test_real_v017_workspace_selects_and_takes_the_teardown_patch(self) -> None: - # An excerpt of the upstream v0.17.0 WORKSPACE: LITERT_REF is not on - # its first line, and the litert archive has its own patch_cmds. - excerpt = ( - Path(build_upstream_runtime.__file__).parent - / "fixtures" - / "litert_lm_v0.17.0_workspace_excerpt.txt" - ).read_text(encoding="utf-8") - self.assertTrue( - build_upstream_runtime.needs_gpu_environment_teardown_patch( - excerpt, "v0.17.0" - ) - ) - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - (root / "WORKSPACE").write_text(excerpt, encoding="utf-8") - build_upstream_runtime.patch_upstream_workspace( - root, patch_bpe_null_piece=True, patch_gpu_environment_teardown=True - ) - patched = (root / "WORKSPACE").read_text(encoding="utf-8") - self.assertIn( - 'http_archive(\n name = "litert",\n patch_args = ["-p1"],\n' - ' patches = ["@//bridge:litert_ios_framework_paths.patch", ' - '"@//bridge:litert_gpu_environment_destroy_callback.patch"],\n' - " patch_cmds = [\n", - patched, - ) - self.assertIn( - 'LITERT_REF = "9fe5be45564c868408e6514c8aabb83e211a0911"\n', patched - ) - - def test_v018_workspace_keeps_tokenizer_and_ios_fixes_without_teardown_patch(self) -> None: - excerpt = (Path(__file__).parent / "fixtures/litert_lm_v0.18.0_workspace_excerpt.txt").read_text() - needs = build_upstream_runtime.needs_gpu_environment_teardown_patch(excerpt, "v0.18.0") - self.assertFalse(needs) - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - (root / "WORKSPACE").write_text(excerpt) - build_upstream_runtime.patch_upstream_workspace( - root, patch_bpe_null_piece=True, patch_gpu_environment_teardown=needs) - patched = (root / "WORKSPACE").read_text() - self.assertIn('patches = ["@//bridge:litert_ios_framework_paths.patch"]', patched) - self.assertIn('patches = ["@//bridge:sentencepiece_bpe_null.patch"]', patched) - self.assertNotIn('litert_gpu_environment_destroy_callback.patch', patched) - self.assertIn('LITERT_REF = "26895c9fbcc25c43faa8c1a98cd1fd28951602c3"', patched) - - def test_gpu_environment_teardown_patch_records_callback_before_opencl(self) -> None: - patch = ( - build_upstream_runtime.BRIDGE_PACKAGE_ROOT - / "bridge" - / "litert_gpu_environment_destroy_callback.patch" - ).read_text(encoding="utf-8") - added = patch.index("+ options_ = CreateGpuEnvironmentOptions(environment_options);") - opencl = patch.index("LITERT_RETURN_IF_ERROR(tflite::gpu::cl::LoadOpenCL().ok())") - removed = patch.index("- options_ = CreateGpuEnvironmentOptions(environment_options);") - self.assertLess(added, opencl) - self.assertLess(opencl, removed) - self.assertIn( - '"litert_gpu_environment_destroy_callback.patch"', - (build_upstream_runtime.BRIDGE_PACKAGE_ROOT / "bridge" / "BUILD.bazel").read_text( - encoding="utf-8" - ), - ) - - def test_legacy_workspace_keeps_litert_archive_unpatched(self) -> None: - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - workspace = root / "WORKSPACE" - workspace.write_text( - "\n".join( - [ - "http_archive(", - ' name = "minizip",', - f' url = "{build_upstream_runtime.ZLIB_URL}",', - ")", - "http_archive(", - ' name = "litert",', - ")", - ] - ), - encoding="utf-8", - ) - - build_upstream_runtime.patch_upstream_workspace( - root, - patch_ios_framework_paths=False, - ) - - patched = workspace.read_text(encoding="utf-8") - self.assertNotIn("litert_ios_framework_paths.patch", patched) - self.assertIn(build_upstream_runtime.ZLIB_GITHUB_MIRROR_URL, patched) - - def test_ios_sampler_uses_embedded_framework_path(self) -> None: - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - sampler = root / "runtime" / "components" / "sampler_factory.cc" - sampler.parent.mkdir(parents=True) - sampler.write_text( - 'auto path = "libLiteRtTopKMetalSampler.dylib";\n', - encoding="utf-8", - ) - - build_upstream_runtime.patch_upstream_ios_sampler_path(root) - - self.assertIn( - "@executable_path/Frameworks/" - "LiteRtTopKMetalSampler.framework/LiteRtTopKMetalSampler", - sampler.read_text(encoding="utf-8"), - ) - def test_windows_stages_materialized_runtime_dlls_only(self) -> None: with tempfile.TemporaryDirectory() as temp: root = Path(temp) @@ -959,11 +608,11 @@ def test_windows_stages_materialized_runtime_dlls_only(self) -> None: (output / "windows" / "x64" / "LiteRt.lib").exists() ) - def test_v017_source_build_stages_the_pinned_dawn_correction(self) -> None: + def test_v020_source_build_stages_the_pinned_dawn_correction(self) -> None: with patch.object( package_upstream_prebuilts, "apply_prebuilt_override" ) as apply_override: - build_upstream_runtime.stage_runtime_overrides("v0.17.0", "android", "arm64") + build_upstream_runtime.stage_runtime_overrides("v0.20.0", "android", "arm64") apply_override.assert_called_once() selected = apply_override.call_args.args[0] self.assertEqual(selected.target_path, "bin/android/arm64/libwebgpu_dawn.so") diff --git a/tools/test_huggingface_token_bytes_patch.py b/tools/test_huggingface_token_bytes_patch.py index f0c02dc..c155165 100644 --- a/tools/test_huggingface_token_bytes_patch.py +++ b/tools/test_huggingface_token_bytes_patch.py @@ -16,24 +16,15 @@ class HuggingFaceTokenBytesPatchTest(unittest.TestCase): - def test_unknown_releases_need_a_new_byte_contract_decision(self) -> None: - for tag in ("v0.17.0", "v0.18.1"): - self.assertFalse(carry.require_token_bytes_patch_decision(tag)) - self.assertEqual(carry.token_bytes_patch_manifest(tag), []) - self.assertTrue(carry.require_token_bytes_patch_decision("v0.19.0")) - for tag in ("v0.19.2", "v0.20.1", "main"): - with self.subTest(tag=tag), self.assertRaisesRegex(RuntimeError, "no explicit decision"): - carry.require_token_bytes_patch_decision(tag) - def test_patch_targets_and_manifest_pin_the_same_exact_sources(self) -> None: text = (REPO / carry.PATCH_PATH).read_text() self.assertEqual(set(re.findall(r"^\+\+\+ b/(\S+)$", text, re.MULTILINE)), set(carry.SOURCES)) self.assertNotIn("sentencepiece_tokenizer", text) - records = carry.token_bytes_patch_manifest("v0.19.0") + records = carry.token_bytes_patch_manifest("v0.20.0") self.assertEqual({entry["source"] for entry in records}, set(carry.SOURCES)) self.assertTrue(all(entry["sha256"] == hashlib.sha256( (REPO / carry.PATCH_PATH).read_bytes()).hexdigest() for entry in records)) - self.assertEqual([entry for entry in source_patch_manifest("v0.19.0") + self.assertEqual([entry for entry in source_patch_manifest("v0.20.0") if entry["id"] == "huggingface-token-bytes"], records) def test_packaged_grammar_controls_reject_incomplete_identity_inputs(self) -> None: @@ -49,12 +40,12 @@ def test_mixed_or_unknown_source_is_refused_before_git_apply(self) -> None: for name in sources: (root / name).write_bytes(b"post") with patch.object(carry, "SOURCES", sources), patch.object(carry, "apply_source_patch") as apply: - carry.apply(root, "v0.19.0") + carry.apply(root, "v0.20.0") apply.assert_not_called() for contents in (b"pre", b"unrecognized"): (root / "one").write_bytes(contents) with self.assertRaisesRegex(RuntimeError, "source changed"): - carry.apply(root, "v0.19.0") + carry.apply(root, "v0.20.0") apply.assert_not_called() def test_successful_git_apply_must_match_every_postimage(self) -> None: @@ -64,7 +55,7 @@ def test_successful_git_apply_must_match_every_postimage(self) -> None: sources = {"one": (hashlib.sha256(b"pre").hexdigest(), hashlib.sha256(b"post").hexdigest())} with patch.object(carry, "SOURCES", sources), patch.object(carry, "apply_source_patch"): with self.assertRaisesRegex(RuntimeError, "postimage mismatch"): - carry.apply(root, "v0.19.0") + carry.apply(root, "v0.20.0") def test_nested_v020_source_applies_and_rejects_a_drifted_postimage(self) -> None: with tempfile.TemporaryDirectory() as temp: @@ -84,8 +75,8 @@ def test_nested_v020_source_applies_and_rejects_a_drifted_postimage(self) -> Non b"--- a/tokenizer.h\n+++ b/tokenizer.h\n" b"@@ -1,2 +1,2 @@\n context\n-raw spelling\n+exact bytes\n" ) - with (patch.object(carry, "V020_SOURCES", sources), - patch.object(carry, "V020_PATCH_PATH", str(patch_file))): + with (patch.object(carry, "SOURCES", sources), + patch.object(carry, "PATCH_PATH", str(patch_file))): source.write_bytes(preimage) carry.apply(root, "v0.20.0") self.assertEqual(source.read_bytes(), postimage) diff --git a/tools/test_ios_runtime_policy.py b/tools/test_ios_runtime_policy.py index dc69b49..bc73f7c 100644 --- a/tools/test_ios_runtime_policy.py +++ b/tools/test_ios_runtime_policy.py @@ -34,9 +34,15 @@ def test_missing_or_changed_source_gate_prevents_build(self) -> None: for text in ("", fixture.replace('"LITERT_LM_FST_CONSTRAINTS_DISABLED": "1"', '"OTHER": "1"'), fixture.replace(':litert_lm_fst_constraints_disabled": []', ':other": []', 1)): gate.write_text(text) - with patch.object(builder, "materialize_git_lfs_libraries"), patch.object(builder, "patch_upstream_ios_sampler_path"), patch.object(builder, "run") as run: + with (patch.object(builder, "materialize_git_lfs_libraries", return_value=0), + patch.object(builder, "verify_carried_dependency_pins"), + patch.object(builder, "patch_asr_untimed_overlap"), + patch.object(builder, "patch_stream_finish_reason"), + patch.object(builder, "patch_huggingface_token_bytes"), + patch.object(builder, "apply_android_gpu_safety"), + patch.object(builder, "run") as run): with self.assertRaisesRegex(RuntimeError, "gate"): - builder.build_runtime(root, "ios", "arm64", "v0.17.0", "1") + builder.build_runtime(root, "ios", "arm64", "v0.20.0", "1") run.assert_not_called() def test_unknown_compatibility_tag_cannot_disable_policy(self) -> None: @@ -173,10 +179,10 @@ def test_source_builder_finalizes_both_source_entry_paths(self) -> None: output = self.build(root / "source", "LiteRtLm") directory = root / "bin/ios/arm64" provider = self.build(directory, "GemmaModelConstraintProvider") - arguments = ["builder", "--upstream-tag", "v0.17.0", "--platform", "ios", "--arch", "arm64"] + arguments = ["builder", "--upstream-tag", "v0.20.0", "--platform", "ios", "--arch", "arm64"] if local_source: arguments += ["--source-root", str(root / "source")] - with patch.object(sys, "argv", arguments), patch.object(builder, "BIN_DIR", root / "bin"), patch.object(builder, "download_upstream", return_value=root / "source"), patch.object(builder, "build_runtime", return_value=output), patch.object(builder, "validate_exported_symbols"), patch.object(builder, "stage_runtime_dependencies"), patch.object(builder, "stage_runtime_overrides"): + with patch.object(sys, "argv", arguments), patch.object(builder, "BIN_DIR", root / "bin"), patch.object(builder, "download_upstream", return_value=root / "source"), patch.object(builder, "build_runtime", return_value=output), patch.object(builder, "validate_exported_symbols"), patch.object(builder, "validate_in_process_litert_linkage"), patch.object(builder, "stage_runtime_dependencies"), patch.object(builder, "stage_runtime_overrides"): self.assertEqual(builder.main(), 0) self.assertFalse(provider.exists()) policy.validate_ios_directory(directory) diff --git a/tools/test_litert_cpu_options_identifier_patch.py b/tools/test_litert_cpu_options_identifier_patch.py deleted file mode 100644 index 640b18e..0000000 --- a/tools/test_litert_cpu_options_identifier_patch.py +++ /dev/null @@ -1,141 +0,0 @@ -from __future__ import annotations - -import hashlib -import re -import subprocess -import tempfile -import unittest -from pathlib import Path -from unittest.mock import MagicMock, patch - -import build_upstream_runtime as build -from asr_overlap_patch import source_patch_manifest, source_sha256 -from litert_cpu_options_identifier_patch import ( - DYNAMIC_RUNTIMES, - LITERT_REF, - PATCH_PATH, - SOURCE, - SOURCES, - cpu_options_identifier_patch_manifest, - require_cpu_options_identifier_patch_decision, - verify_dynamic_runtime, -) -from test_workspace_build_patch import stage_v0181 - -REPO = Path(__file__).resolve().parents[1] -PATCH = (REPO / PATCH_PATH).read_text(encoding="utf-8") -FIXTURE = REPO / "tools/fixtures/litert_cpu_options_ca21dc99.cc" - - -class CpuOptionsIdentifierPatchTest(unittest.TestCase): - def test_decision_applies_only_to_v0181(self) -> None: - for tag in ("v0.17.1", "v0.18.0"): - self.assertFalse(require_cpu_options_identifier_patch_decision(tag)) - self.assertEqual(cpu_options_identifier_patch_manifest(tag), []) - self.assertTrue(require_cpu_options_identifier_patch_decision("v0.18.1")) - for tag in ("v0.18.2", "v0.19.2", "main"): - with self.subTest(tag=tag), self.assertRaisesRegex( - RuntimeError, "no explicit decision" - ): - require_cpu_options_identifier_patch_decision(tag) - - def test_patch_changes_only_the_identifier_to_the_prebuilt_one(self) -> None: - self.assertEqual(re.findall(r"^diff --git a/(\S+) b/\1$", PATCH, re.MULTILINE), [SOURCE]) - removed = re.findall(r"^-(?!-- )(.*)$", PATCH, re.MULTILINE) - added = [line for line in re.findall(r"^\+(?!\+\+ )(.*)$", PATCH, re.MULTILINE) - if not line.startswith("//")] - self.assertEqual(removed, ['const char* LrtGetCpuOptionsIdentifier() { return "cpu_options"; }']) - self.assertEqual(added, ['const char* LrtGetCpuOptionsIdentifier() { return "xnnpack"; }']) - - def test_patch_turns_the_pinned_preimage_into_the_postimage(self) -> None: - preimage, postimage = SOURCES[SOURCE] - self.assertEqual(source_sha256(FIXTURE.read_bytes()), preimage) - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - (root / SOURCE).parent.mkdir(parents=True) - (root / SOURCE).write_bytes(FIXTURE.read_bytes()) - subprocess.run(["git", "apply", str(REPO / PATCH_PATH)], cwd=root, check=True) - self.assertEqual(source_sha256((root / SOURCE).read_bytes()), postimage) - - def test_v0181_workspace_patches_the_litert_archive(self) -> None: - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - stage_v0181(root) - build.patch_workspace_build(root, "v0.18.1") - build.patch_upstream_workspace(root, patch_cpu_options_identifier=True) - workspace = (root / "WORKSPACE").read_text(encoding="utf-8") - self.assertIn('"@//bridge:litert_cpu_options_identifier.patch"]', workspace) - refs = re.findall(r'^LITERT_REF = "([0-9a-f]{40})"$', workspace, re.MULTILINE) - self.assertEqual(refs[-1], LITERT_REF) - self.assertIn('"litert_cpu_options_identifier.patch"', - (REPO / "native/bridge/BUILD.bazel").read_text(encoding="utf-8")) - - def test_dynamic_hosts_require_the_audited_prebuilt_runtime(self) -> None: - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - name, _ = DYNAMIC_RUNTIMES[("linux", "arm64")] - (root / name).parent.mkdir(parents=True) - (root / name).write_bytes(b"newer runtime") - with self.assertRaisesRegex(RuntimeError, "requalify"): - verify_dynamic_runtime(root, "linux", "arm64") - with self.assertRaisesRegex(RuntimeError, "requalify"): - verify_dynamic_runtime(root, "windows", "x64") - verify_dynamic_runtime(root, "macos", "arm64") - verify_dynamic_runtime(root, "android", "arm64") - with patch("litert_cpu_options_identifier_patch.DYNAMIC_RUNTIMES", - {("linux", "arm64"): (name, hashlib.sha256(b"newer runtime").hexdigest())}): - verify_dynamic_runtime(root, "linux", "arm64") - - def test_build_checks_runtime_and_postimage_only_for_v0181(self) -> None: - for tag, checked in (("v0.18.0", False), ("v0.18.1", True)): - calls = MagicMock() - with self.subTest(tag=tag), tempfile.TemporaryDirectory() as temp, \ - patch.object(build, "verify_carried_dependency_pins"), \ - patch.object(build, "fetch_audited_archives"), \ - patch.object(build, "patch_asr_untimed_overlap"), \ - patch.object(build, "patch_asr_litertlm_container"), \ - patch.object(build, "patch_stream_finish_reason"), \ - patch.object(build, "materialize_git_lfs_libraries", return_value=0), \ - patch.object(build, "bazel_command", return_value=["bazel"]), \ - patch.object(build, "run", calls.run), \ - patch.object(build, "verify_xnnpack_postimages"), \ - patch.object(build, "verify_dynamic_runtime", calls.runtime), \ - patch.object(build, "verify_cpu_options_identifier_postimage", calls.postimage): - root = Path(temp) - with self.assertRaisesRegex(RuntimeError, "Expected build output missing"): - build.build_runtime(root, "linux", "arm64", tag, "2") - names = [name for name, _, _ in calls.mock_calls] - self.assertEqual(names, ["runtime", "run", "postimage"] if checked else ["run"]) - if checked: - calls.runtime.assert_called_once_with(root / "prebuilt", "linux", "arm64") - calls.postimage.assert_called_once_with(root) - - def test_postimage_check_reads_the_bazel_litert_repository(self) -> None: - with tempfile.TemporaryDirectory() as temp: - output_base = Path(temp) / "output_base" - source_root = Path(temp) / "source" - exec_root = output_base / "execroot" / "litert_lm" - (exec_root / "bazel-out").mkdir(parents=True) - source_root.mkdir() - (source_root / "bazel-out").symlink_to(exec_root / "bazel-out") - source = output_base / "external" / "litert" / SOURCE - source.parent.mkdir(parents=True) - source.write_bytes(FIXTURE.read_bytes()) - with self.assertRaisesRegex(RuntimeError, "postimage mismatch"): - build.verify_cpu_options_identifier_postimage(source_root) - subprocess.run(["git", "apply", str(REPO / PATCH_PATH)], - cwd=output_base / "external" / "litert", check=True) - build.verify_cpu_options_identifier_postimage(source_root) - - def test_manifest_records_the_rollback_last(self) -> None: - records = source_patch_manifest("v0.18.1") - self.assertEqual(records[-1:], cpu_options_identifier_patch_manifest("v0.18.1")) - record = records[-1] - self.assertEqual(record["id"], "litert-cpu-options-identifier") - self.assertEqual(record["sha256"], hashlib.sha256((REPO / PATCH_PATH).read_bytes()).hexdigest()) - self.assertEqual(record["source"], f"LiteRT@{LITERT_REF}/{SOURCE}") - self.assertEqual((record["preimageSha256Lf"], record["postimageSha256Lf"]), SOURCES[SOURCE]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_litert_lm_finish_reason_smoke.py b/tools/test_litert_lm_finish_reason_smoke.py index 49b8201..2e9c7ea 100644 --- a/tools/test_litert_lm_finish_reason_smoke.py +++ b/tools/test_litert_lm_finish_reason_smoke.py @@ -67,10 +67,11 @@ def test_message_is_a_single_user_text_turn(self) -> None: ) def test_abi_only_expects_version_one_only_for_patched_tags(self) -> None: - self.assertEqual(smoke.expected_abi_version("v0.18.0"), 1) - self.assertEqual(smoke.expected_abi_version("v0.17.1"), 0) + self.assertEqual(smoke.expected_abi_version("v0.20.0"), 1) + with self.assertRaisesRegex(RuntimeError, "historical native release ref"): + smoke.expected_abi_version("v0.19.1") with self.assertRaisesRegex(RuntimeError, "no explicit decision"): - smoke.expected_abi_version("v0.19.2") + smoke.expected_abi_version("v0.20.1") def test_abi_only_requires_the_tag_in_process_litert_marker(self) -> None: with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): @@ -83,7 +84,7 @@ def test_abi_only_requires_the_tag_in_process_litert_marker(self) -> None: self.assertEqual(smoke.in_process_litert_matches(library, tag), expected) def test_abi_only_main_fails_when_the_in_process_marker_mismatches(self) -> None: - tag = "v0.19.1" + tag = "v0.20.0" for marker, expected_status in ((1, 0), (0, 1)): library = SimpleNamespace( stream_proxy_finish_reason_abi_version=Mock( @@ -94,7 +95,8 @@ def test_abi_only_main_fails_when_the_in_process_marker_mismatches(self) -> None "--upstream-tag", tag] with self.subTest(marker=marker), \ patch.object(sys, "argv", argv), \ - patch.object(smoke, "bind", return_value=SimpleNamespace(library=library)), \ + patch.object(smoke, "bind", return_value=SimpleNamespace( + library=library, api_version=lambda: (1, 1, 0))), \ redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): self.assertEqual(smoke.main(), expected_status) diff --git a/tools/test_litert_stage_spatial_tensors_patch.py b/tools/test_litert_stage_spatial_tensors_patch.py index dfb192e..b7f25e0 100644 --- a/tools/test_litert_stage_spatial_tensors_patch.py +++ b/tools/test_litert_stage_spatial_tensors_patch.py @@ -12,7 +12,6 @@ PATCH_PATH, SOURCES, UPSTREAM_FIX, - require_stage_spatial_tensors_patch_decision, stage_spatial_tensors_patch_manifest, ) @@ -20,15 +19,6 @@ class StageSpatialTensorsPatchTest(unittest.TestCase): - def test_requires_a_version_specific_decision(self) -> None: - for tag in ("v0.18.1", "v0.19.0"): - self.assertFalse(require_stage_spatial_tensors_patch_decision(tag)) - self.assertEqual(stage_spatial_tensors_patch_manifest(tag), []) - self.assertTrue(require_stage_spatial_tensors_patch_decision("v0.19.1")) - for tag in ("v0.19.2", "main"): - with self.subTest(tag=tag), self.assertRaisesRegex(RuntimeError, "no explicit decision"): - stage_spatial_tensors_patch_manifest(tag) - @unittest.skipUnless(os.environ.get("LITERT_STAGE_SPATIAL_TENSORS_SOURCE"), "requires the pinned unpatched LiteRT source tree") def test_backport_matches_the_pinned_preimages_and_postimages(self) -> None: @@ -48,8 +38,8 @@ def test_manifest_attributes_exactly_the_four_patched_sources(self) -> None: patch = (REPO / PATCH_PATH).read_bytes() headers = re.findall(rb"^diff --git a/(\S+) b/\1$", patch, re.MULTILINE) self.assertEqual([path.decode() for path in headers], list(SOURCES)) - records = stage_spatial_tensors_patch_manifest("v0.19.1") - self.assertEqual(source_patch_manifest("v0.19.1")[-len(records):], records) + records = stage_spatial_tensors_patch_manifest("v0.20.0") + self.assertEqual(source_patch_manifest("v0.20.0")[-len(records):], records) self.assertEqual(len(records), len(SOURCES)) for record, (path, (preimage, postimage)) in zip(records, SOURCES.items()): self.assertEqual(record["id"], "litert-stage-spatial-tensors") diff --git a/tools/test_macos_runtime_policy.py b/tools/test_macos_runtime_policy.py index af29745..bdf2539 100644 --- a/tools/test_macos_runtime_policy.py +++ b/tools/test_macos_runtime_policy.py @@ -337,7 +337,7 @@ def test_no_build_matrix_or_target_produces_macos_x64(self) -> None: self.assertIn('"platform": "macos", "arch": "arm64"', workflow) self.assertNotIn('"platform": "macos", "arch": "x64"', workflow) with patch.object(sys, "argv", [ - "build_upstream_runtime.py", "--upstream-tag", "v0.18.0", + "build_upstream_runtime.py", "--upstream-tag", "v0.20.0", "--platform", "macos", "--arch", "x64", ]): with self.assertRaisesRegex(SystemExit, "macos/x64: macOS runtimes are published for arm64 only"): diff --git a/tools/test_package_release.py b/tools/test_package_release.py index 382ade7..7552bb6 100644 --- a/tools/test_package_release.py +++ b/tools/test_package_release.py @@ -21,13 +21,13 @@ class PackageReleaseTest(unittest.TestCase): def test_newer_upstream_requires_asr_decision_before_release_io(self) -> None: with patch.object(package_release, "iter_artifacts", side_effect=AssertionError("release I/O")): - with self.assertRaisesRegex(RuntimeError, "ASR untimed overlap has no explicit decision"): + with self.assertRaisesRegex(RuntimeError, "LiteRT-LM source carries have no explicit decision"): package_release.build_manifest( - upstream_tag="v0.19.2", upstream_commit=UPSTREAM_COMMIT, - compatibility_tag="v0.19.2", release_tag="v0.19.2-1", + upstream_tag="v0.20.1", upstream_commit=UPSTREAM_COMMIT, + compatibility_tag="v0.20.1", release_tag="v0.20.1-1", native_commit=NATIVE_COMMIT, official_upstream_assets=True) - def test_v018_source_patch_provenance_is_emitted_and_validated(self) -> None: + def test_v020_source_patch_provenance_is_emitted_and_validated(self) -> None: import hashlib from asr_overlap_patch import PATCH_PATH, PREIMAGE_SHA256, POSTIMAGE_SHA256 from validate_release_manifest import validate_schema_2_identity @@ -36,8 +36,8 @@ def test_v018_source_patch_provenance_is_emitted_and_validated(self) -> None: patch.object(package_release, "provider_free_ios", return_value=False), patch.object(package_release, "SHA256SUMS_PATH", Path(temp) / "SHA256SUMS")): manifest = package_release.build_manifest( - upstream_tag="v0.18.0", upstream_commit=UPSTREAM_COMMIT, - compatibility_tag="v0.18.0", release_tag="v0.18.0-1", + upstream_tag="v0.20.0", upstream_commit=UPSTREAM_COMMIT, + compatibility_tag="v0.20.0", release_tag="v0.20.0-1", native_commit=NATIVE_COMMIT, official_upstream_assets=True) from stream_finish_reason_patch import ( PATCH_PATH as FINISH_REASON_PATCH_PATH, @@ -45,9 +45,12 @@ def test_v018_source_patch_provenance_is_emitted_and_validated(self) -> None: ) records = manifest["upstream"]["sourcePatches"] self.assertEqual([record["id"] for record in records], - ["asr-untimed-overlap"] + ["asr-litertlm-container"] * 3 - + ["stream-finish-reason"] * len(FINISH_REASON_SOURCES)) - finish_records = records[-len(FINISH_REASON_SOURCES):] + ["asr-untimed-overlap"] + ["stream-finish-reason"] * len(FINISH_REASON_SOURCES) + + ["android-qwen3-gpu-safety"] * 2 + ["windows-engine-fd"] + + ["xnnpack-pf32-sme2"] * 4 + ["xnnpack-pqs8-qc4w-sme2"] + + ["huggingface-token-bytes"] * 6 + + ["litert-stage-spatial-tensors"] * 4) + finish_records = [r for r in records if r["id"] == "stream-finish-reason"] finish_reason_sha256 = hashlib.sha256( (Path(__file__).resolve().parents[1] / FINISH_REASON_PATCH_PATH).read_bytes() ).hexdigest() @@ -63,9 +66,9 @@ def test_v018_source_patch_provenance_is_emitted_and_validated(self) -> None: self.assertEqual(records[0]["postimageSha256Lf"], POSTIMAGE_SHA256) def validate(): validate_schema_2_identity( - manifest, upstream_tag="v0.18.0", upstream_commit=UPSTREAM_COMMIT, - compatibility_tag="v0.18.0", native_commit=NATIVE_COMMIT, - release_tag="v0.18.0-1") + manifest, upstream_tag="v0.20.0", upstream_commit=UPSTREAM_COMMIT, + compatibility_tag="v0.20.0", native_commit=NATIVE_COMMIT, + release_tag="v0.20.0-1") validate() tampered = deepcopy(records) records[-1]["postimageSha256Lf"] = "0" * 64 diff --git a/tools/test_package_upstream_prebuilts.py b/tools/test_package_upstream_prebuilts.py index 2e659bf..f65d234 100644 --- a/tools/test_package_upstream_prebuilts.py +++ b/tools/test_package_upstream_prebuilts.py @@ -152,7 +152,7 @@ def test_override_application_can_be_scoped_to_one_target(self) -> None: "apply_prebuilt_override", ) as apply_override: count = package_upstream_prebuilts.apply_prebuilt_overrides( - "v0.16.0", + "v0.20.0", platform="android", arch="arm64", ) @@ -163,13 +163,13 @@ def test_override_application_can_be_scoped_to_one_target(self) -> None: self.assertEqual(selected.platform, "android") self.assertEqual(selected.arch, "arm64") - def test_v017_override_is_applied_only_to_requested_android_target(self) -> None: + def test_v020_override_is_applied_only_to_requested_android_target(self) -> None: for arch in ("arm64", "x64"): with self.subTest(arch=arch), patch.object( package_upstream_prebuilts, "apply_prebuilt_override" ) as apply_override: count = package_upstream_prebuilts.apply_prebuilt_overrides( - "v0.17.0", platform="android", arch=arch + "v0.20.0", platform="android", arch=arch ) self.assertEqual(count, 1) apply_override.assert_called_once() @@ -178,12 +178,12 @@ def test_v017_override_is_applied_only_to_requested_android_target(self) -> None with patch.object(package_upstream_prebuilts, "apply_prebuilt_override") as apply_override: self.assertEqual(package_upstream_prebuilts.apply_prebuilt_overrides( - "v0.17.0", platform="macos", arch="arm64" + "v0.20.0", platform="macos", arch="arm64" ), 0) apply_override.assert_not_called() - def test_v017_bad_override_checksum_preserves_existing_library(self) -> None: - override = package_upstream_prebuilts.prebuilt_overrides("v0.17.0")[0] + def test_v020_bad_override_checksum_preserves_existing_library(self) -> None: + override = package_upstream_prebuilts.prebuilt_overrides("v0.20.0")[0] with tempfile.TemporaryDirectory() as temp: output = Path(temp) target = output / override.platform / override.arch / override.filename diff --git a/tools/test_prebuilt_overrides.py b/tools/test_prebuilt_overrides.py index 72bf211..d0d1de3 100644 --- a/tools/test_prebuilt_overrides.py +++ b/tools/test_prebuilt_overrides.py @@ -4,39 +4,16 @@ from prebuilt_overrides import ( ANDROID_DAWN_ROLLBACK_COMMIT, - V0_15_ANDROID_SAMPLER_FIX_COMMIT, prebuilt_override_manifest, prebuilt_overrides, ) class PrebuiltOverridesTest(unittest.TestCase): - def test_v015_pins_android_corrections_for_both_architectures(self) -> None: - overrides = prebuilt_overrides("v0.15.0") - - self.assertEqual({override.arch for override in overrides}, {"arm64", "x64"}) - self.assertEqual( - {(override.arch, override.filename) for override in overrides}, - { - ("arm64", "libLiteRtTopKOpenClSampler.so"), - ("x64", "libLiteRtTopKOpenClSampler.so"), - ("arm64", "libwebgpu_dawn.so"), - ("x64", "libwebgpu_dawn.so"), - }, - ) - self.assertEqual( - {override.source_commit for override in overrides}, - { - V0_15_ANDROID_SAMPLER_FIX_COMMIT, - ANDROID_DAWN_ROLLBACK_COMMIT, - }, - ) - self.assertTrue(all(len(override.sha256) == 64 for override in overrides)) - def test_manifest_records_exact_override_provenance(self) -> None: - manifest = prebuilt_override_manifest("v0.15.0") + manifest = prebuilt_override_manifest("v0.20.0") - self.assertEqual(len(manifest), 4) + self.assertEqual(len(manifest), 2) self.assertTrue( all( entry["sourceRepository"] == "google-ai-edge/LiteRT-LM" @@ -50,12 +27,6 @@ def test_manifest_records_exact_override_provenance(self) -> None: for entry in manifest }, { - "bin/android/arm64/libLiteRtTopKOpenClSampler.so": ( - V0_15_ANDROID_SAMPLER_FIX_COMMIT - ), - "bin/android/x64/libLiteRtTopKOpenClSampler.so": ( - V0_15_ANDROID_SAMPLER_FIX_COMMIT - ), "bin/android/arm64/libwebgpu_dawn.so": ( ANDROID_DAWN_ROLLBACK_COMMIT ), @@ -66,7 +37,7 @@ def test_manifest_records_exact_override_provenance(self) -> None: ) def test_supported_versions_keep_the_validated_android_dawn_rollback(self) -> None: - for tag in ("v0.16.0", "v0.16.1", "v0.17.0", "v0.17.1", "v0.18.0", "v0.18.1"): + for tag in ("v0.20.0",): with self.subTest(tag=tag): self._assert_dawn_rollback(tag) @@ -96,6 +67,7 @@ def _assert_dawn_rollback(self, tag: str) -> None: def test_v0171_preserves_exact_v0170_override_provenance(self) -> None: self.assertEqual(prebuilt_override_manifest("v0.17.1"), prebuilt_override_manifest("v0.17.0")) + self.assertEqual(prebuilt_overrides("v0.17.0"), ()) self.assertEqual(prebuilt_overrides("v0.17.2"), ()) def test_other_versions_have_no_override(self) -> None: diff --git a/tools/test_step_zero_state_patch.py b/tools/test_step_zero_state_patch.py deleted file mode 100644 index 1431b1b..0000000 --- a/tools/test_step_zero_state_patch.py +++ /dev/null @@ -1,59 +0,0 @@ -import hashlib -import tempfile -import unittest -from pathlib import Path -from unittest.mock import patch - -import step_zero_state_patch as carry -from asr_overlap_patch import source_patch_manifest - - -class StepZeroStatePatchTest(unittest.TestCase): - def test_manifest_attributes_only_the_v0191_executor(self) -> None: - self.assertEqual(carry.manifest("v0.19.0"), []) - with self.assertRaisesRegex(RuntimeError, "no explicit decision"): - carry.manifest("v0.19.2") - records = [record for record in source_patch_manifest("v0.19.1") - if record["id"] == "step-zero-state"] - self.assertEqual(records, [{ - "id": "step-zero-state", - "path": carry.PATCH_PATH, - "sha256": hashlib.sha256((Path(__file__).resolve().parents[1] / carry.PATCH_PATH).read_bytes()).hexdigest(), - "source": carry.SOURCE, - "preimageSha256Lf": carry.PREIMAGE, - "postimageSha256Lf": "b2c73fbcb400654072bf926dbaa3b81e252acf750f8fc1a60dd0b51df84d890d", - "scope": "source-built runtimes only; excludes official upstream prebuilts", - }]) - patch_path = Path(__file__).resolve().parents[1] / carry.PATCH_PATH - headers = [line for line in patch_path.read_text().splitlines() - if line.startswith(("--- ", "+++ "))] - self.assertEqual(headers, [f"--- a/{carry.SOURCE}", f"+++ b/{carry.SOURCE}"]) - - def test_version_bound_application_is_idempotent_and_rejects_wrong_source(self) -> None: - before = b"old executor\n" - after = b"new executor\n" - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - source = root / carry.SOURCE - source.parent.mkdir(parents=True) - patch_path = root / "fixture.patch" - patch_path.write_text(f"--- a/{carry.SOURCE}\n+++ b/{carry.SOURCE}\n" - "@@ -1 +1 @@\n-old executor\n+new executor\n") - with (patch.object(carry, "PATCH_PATH", str(patch_path)), - patch.object(carry, "PREIMAGE", hashlib.sha256(before).hexdigest()), - patch.object(carry, "POSTIMAGE", hashlib.sha256(after).hexdigest())): - source.write_bytes(before) - carry.apply(root, "v0.19.1") - self.assertEqual(source.read_bytes(), after) - with patch.object(carry, "apply_source_patch") as apply: - carry.apply(root, "v0.19.1") - source.write_bytes(b"unknown executor\n") - with self.assertRaisesRegex(RuntimeError, "source changed"): - carry.apply(root, "v0.19.1") - apply.assert_not_called() - - def test_application_requires_the_exact_postimage(self) -> None: - with (patch.object(carry, "_digest", side_effect=[carry.PREIMAGE, "wrong"]), - patch.object(carry, "apply_source_patch")): - with self.assertRaisesRegex(RuntimeError, "postimage mismatch"): - carry.apply(Path("."), "v0.19.1") diff --git a/tools/test_stream_finish_reason_patch.py b/tools/test_stream_finish_reason_patch.py index 1c69ea6..0e05bba 100644 --- a/tools/test_stream_finish_reason_patch.py +++ b/tools/test_stream_finish_reason_patch.py @@ -12,8 +12,6 @@ BAZEL_DEFINE, PATCH_PATH, SOURCES, - finish_reason_patch_manifest, - require_finish_reason_patch_decision, ) REPO_ROOT = Path(__file__).resolve().parents[1] @@ -23,24 +21,11 @@ class StreamFinishReasonPatchTest(unittest.TestCase): - def test_decision_applies_only_to_audited_v018(self) -> None: - for tag in ("v0.15.0", "v0.16.1", "v0.17.1"): - self.assertFalse(require_finish_reason_patch_decision(tag)) - self.assertEqual(finish_reason_patch_manifest(tag), []) - for tag in ("v0.18.0", "v0.18.1"): - self.assertTrue(require_finish_reason_patch_decision(tag)) - for tag in ("v0.18.2", "v0.19.2", "main"): - with self.subTest(tag=tag), self.assertRaisesRegex( - RuntimeError, "no explicit decision" - ): - require_finish_reason_patch_decision(tag) - - def test_patch_is_plain_and_touches_exactly_the_pinned_sources(self) -> None: + def test_patch_touches_exactly_the_pinned_sources(self) -> None: targets = re.findall(r"^\+\+\+ b/(\S+)$", PATCH, re.MULTILINE) sources = re.findall(r"^--- a/(\S+)$", PATCH, re.MULTILINE) self.assertEqual(sorted(targets), sorted(SOURCES)) self.assertEqual(sources, targets) - self.assertNotRegex(PATCH, r"(?m)^(diff --git|index )") def test_runtime_and_bridge_share_finish_reason_wire_values(self) -> None: runtime = { @@ -68,18 +53,18 @@ def test_bazel_define_selects_the_bridge_finish_reason_api(self) -> None: self.assertIn(f'define_values = {{"{key}": "{value}"}}', BRIDGE_BUILD) self.assertIn('":finish_reason_api": ["LITERT_LM_FINISH_REASON_API=1"]', BRIDGE_BUILD) - self.assertIn('"stream_finish_reason.patch"', BRIDGE_BUILD) + self.assertIn('name = "finish_reason_api"', BRIDGE_BUILD) - def test_build_applies_patch_and_define_only_for_v018(self) -> None: - for tag, expected in (("v0.17.1", False), ("v0.18.0", True), ("v0.18.1", True)): + def test_build_applies_patch_and_enables_finish_reason(self) -> None: + for tag, expected in (("v0.20.0", True),): with self.subTest(tag=tag), tempfile.TemporaryDirectory() as temp: root = Path(temp) with patch.object(build_upstream_runtime, "materialize_git_lfs_libraries", return_value=0), \ patch.object(build_upstream_runtime, "verify_carried_dependency_pins"), \ patch.object(build_upstream_runtime, "fetch_audited_archives"), \ + patch.object(build_upstream_runtime, "patch_huggingface_token_bytes"), \ + patch.object(build_upstream_runtime, "apply_android_gpu_safety"), \ patch.object(build_upstream_runtime, "patch_asr_untimed_overlap"), \ - patch.object(build_upstream_runtime, "patch_asr_litertlm_container"), \ - patch.object(build_upstream_runtime, "patch_upstream_ios_sampler_path"), \ patch.object(build_upstream_runtime, "patch_stream_finish_reason") as apply, \ patch.object(build_upstream_runtime, "bazel_command", return_value=["bazel"]), \ patch.object(build_upstream_runtime, "run", side_effect=RuntimeError("captured build")) as run: @@ -94,9 +79,9 @@ def test_patch_fails_closed_on_unaudited_source(self) -> None: for name in SOURCES: path = root / name path.parent.mkdir(parents=True, exist_ok=True) - path.write_text("// not the audited v0.18.0 source\n") + path.write_text("// not the audited v0.20.0 source\n") with self.assertRaisesRegex(RuntimeError, "requalify the stream finish-reason patch"): - build_upstream_runtime.patch_stream_finish_reason(root, "v0.18.0") + build_upstream_runtime.patch_stream_finish_reason(root, "v0.20.0") build_upstream_runtime.patch_stream_finish_reason(root, "v0.17.1") def _fake_sources(self, root: Path) -> dict[str, tuple[str, str]]: @@ -118,9 +103,9 @@ def git_apply(command, **_kwargs): for name in sources: (root / name).write_text(f"{git_apply_writes} {name}\n") - with patch.object(build_upstream_runtime, "finish_reason_patch_sources", return_value=sources), \ + with patch.object(build_upstream_runtime, "FINISH_REASON_SOURCES", sources), \ patch.object(build_upstream_runtime.subprocess, "run", side_effect=git_apply) as run: - build_upstream_runtime.patch_stream_finish_reason(root, "v0.18.0") + build_upstream_runtime.patch_stream_finish_reason(root, "v0.20.0") return run def test_patch_applies_to_preimage_and_checks_postimage(self) -> None: diff --git a/tools/test_stream_proxy_callback_abi.py b/tools/test_stream_proxy_callback_abi.py index 40577de..0251190 100644 --- a/tools/test_stream_proxy_callback_abi.py +++ b/tools/test_stream_proxy_callback_abi.py @@ -154,19 +154,17 @@ def test_all_bazel_targets_select_the_metadata_callback_mode(self) -> None: self.assertIn('define_values = {"litert_lm_stream_chunk_api": "true"}', source) self.assertIn('\":stream_chunk_api\": [\"LITERT_LM_STREAM_CHUNK_API=1\"]', source) for platform, arch in build_upstream_runtime.RUNTIME_TARGETS: - for tag, expected in (("v0.14.0", 1), ("v0.15.0", 2), ("v0.19.0", 2)): + for tag, expected in (("v0.20.0", 2),): with self.subTest(platform=platform, arch=arch, tag=tag), tempfile.TemporaryDirectory() as temp, ExitStack() as mocks: for name in ( - "patch_asr_untimed_overlap", "patch_asr_litertlm_container", + "patch_asr_untimed_overlap", "patch_stream_finish_reason", "patch_huggingface_token_bytes", - "apply_android_gpu_safety", "patch_upstream_ios_sampler_path", + "apply_android_gpu_safety", "patch_windows_engine_fd", "patch_windows_rules_android", "verify_upstream_fst_gate", "verify_carried_dependency_pins", "fetch_audited_archives", ): mocks.enter_context(patch.object(build_upstream_runtime, name)) mocks.enter_context(patch.object(build_upstream_runtime, "materialize_git_lfs_libraries", return_value=0)) - mocks.enter_context(patch.object(build_upstream_runtime, "require_cpu_options_identifier_patch_decision", return_value=False)) - mocks.enter_context(patch.object(build_upstream_runtime, "require_finish_reason_patch_decision", return_value=False)) mocks.enter_context(patch.object(build_upstream_runtime, "prepare_bridge_package", return_value=[])) mocks.enter_context(patch.object(build_upstream_runtime, "bazel_command", return_value=["bazel"])) run = mocks.enter_context(patch.object(build_upstream_runtime, "run", side_effect=RuntimeError("captured build"))) diff --git a/tools/test_v0181_qualification.py b/tools/test_v0181_qualification.py deleted file mode 100644 index 66fd8bc..0000000 --- a/tools/test_v0181_qualification.py +++ /dev/null @@ -1,111 +0,0 @@ -from __future__ import annotations - -from copy import deepcopy -import tempfile -import unittest -from pathlib import Path -from unittest.mock import patch - -import build_upstream_runtime as build -import package_release -from asr_litertlm_container_patch import SOURCES -from asr_overlap_patch import POSTIMAGE_SHA256, source_patch_manifest, source_sha256 -from litert_cpu_options_identifier_patch import cpu_options_identifier_patch_manifest -from stream_finish_reason_patch import BAZEL_DEFINE as FINISH_REASON_DEFINE, finish_reason_patch_manifest -from workspace_build_patch import workspace_build_patch_manifest -from xnnpack_pf32_sme2_patch import xnnpack_pf32_patch_manifest -from xnnpack_pqs8_qc4w_sme2_patch import xnnpack_qc4w_patch_manifest -from prebuilt_overrides import ANDROID_DAWN_ROLLBACKS, prebuilt_overrides -from test_asr_litertlm_container_patch import stage_preimage -from test_workspace_build_patch import stage_v0181 -from validate_release_manifest import validate_schema_2_identity - -REPO = Path(__file__).resolve().parents[1] -UPSTREAM_COMMIT = "bda624851d74be34d4e1f7fac1fc4155939539c7" -NATIVE_COMMIT = "8182448814867ad329be7e995b4e8aab5efd79c8" - - -class V0181QualificationTest(unittest.TestCase): - def test_v0181_production_build_applies_all_three_source_carries_before_bazel(self): - # These fixtures are byte-identical in exact v0.18.0 and v0.18.1. - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - stage_preimage(root) - stage_v0181(root) - build.patch_workspace_build(root, "v0.18.1") - build.patch_upstream_workspace( - root, patch_bpe_null_piece=True, patch_xnnpack_pf32_sme2=True, - patch_cpu_options_identifier=True, - ) - merger = root / "omni/asr/timestamp_text_merger.cc" - merger.write_bytes((REPO / "tools/fixtures/timestamp_text_merger_v018.cc").read_bytes()) - with (patch.object(build, "materialize_git_lfs_libraries", return_value=0), - patch.object(build, "patch_stream_finish_reason") as finish_reason, - patch.object(build, "bazel_command", return_value=["bazel"]), - patch.object(build, "fetch_audited_archives"), - patch.object(build, "run", side_effect=RuntimeError("reached Bazel")) as run): - with self.assertRaisesRegex(RuntimeError, "reached Bazel"): - build.build_runtime(root, "macos", "arm64", "v0.18.1", "2") - # Finish-reason source application is covered with fixtures in - # test_stream_finish_reason_patch; here only its v0.18.1 wiring. - finish_reason.assert_called_once_with(root, "v0.18.1") - self.assertIn(FINISH_REASON_DEFINE, run.call_args.args[0]) - self.assertEqual(source_sha256(merger.read_bytes()), POSTIMAGE_SHA256) - for source, (_, postimage) in SOURCES.items(): - self.assertEqual(source_sha256((root / source).read_bytes()), postimage) - self.assertIn("--define=litert_lm_asr_api=true", run.call_args.args[0]) - # Exact idempotence and drift rejection also apply to the new tag. - build.patch_asr_untimed_overlap(root, "v0.18.1") - build.patch_asr_litertlm_container(root, "v0.18.1") - merger.write_bytes(merger.read_bytes() + b"// drift\n") - with (patch.object(build, "patch_stream_finish_reason"), - self.assertRaisesRegex(RuntimeError, "requalify untimed overlap")): - build.build_runtime(root, "macos", "arm64", "v0.18.1", "2") - - def test_v0181_manifest_keeps_all_patch_and_dawn_records_and_rejects_loss(self): - with tempfile.TemporaryDirectory() as temp: - with (patch.object(package_release, "iter_artifacts", return_value=[]), - patch.object(package_release, "provider_free_ios", return_value=False), - patch.object(package_release, "SHA256SUMS_PATH", Path(temp) / "SHA256SUMS")): - manifest = package_release.build_manifest( - upstream_tag="v0.18.1", upstream_commit=UPSTREAM_COMMIT, - compatibility_tag="v0.18.1", release_tag="v0.18.1", - native_commit=NATIVE_COMMIT, official_upstream_assets=True) - self.assertEqual(manifest["upstream"]["sourcePatches"], - source_patch_manifest("v0.18.0") + workspace_build_patch_manifest("v0.18.1") - + xnnpack_pf32_patch_manifest("v0.18.1") - + xnnpack_qc4w_patch_manifest("v0.18.1") - + cpu_options_identifier_patch_manifest("v0.18.1")) - self.assertEqual(finish_reason_patch_manifest("v0.18.1"), finish_reason_patch_manifest("v0.18.0")) - self.assertTrue({"stream-finish-reason", "asr-untimed-overlap", "workspace-build", "xnnpack-pf32-sme2", - "xnnpack-pqs8-qc4w-sme2", "litert-cpu-options-identifier"} - <= {entry["id"] for entry in manifest["upstream"]["sourcePatches"]}) - self.assertEqual(prebuilt_overrides("v0.18.1"), ANDROID_DAWN_ROLLBACKS) - def validate(value): - validate_schema_2_identity(value, upstream_tag="v0.18.1", upstream_commit=UPSTREAM_COMMIT, - compatibility_tag="v0.18.1", native_commit=NATIVE_COMMIT, - release_tag="v0.18.1") - validate(manifest) - for field in ("sourcePatches", "prebuiltOverrides"): - broken = deepcopy(manifest) - broken["upstream"][field] = [] - with self.subTest(field=field), self.assertRaises(SystemExit): - validate(broken) - - def test_gpu_teardown_selection_follows_last_starlark_assignment(self): - old = next(iter(build.LITERT_REFS_WITHOUT_GPU_TEARDOWN_ORDERING)) - new = "ca21dc99de51c76bdcc572afeea1dd937d3c9e5c" - # Stable v0.18.1 retains an old assignment before the effective one. - for first, last, needs in ((old, new, False), (new, old, True)): - with self.subTest(last=last): - self.assertEqual(build.needs_gpu_environment_teardown_patch( - f'LITERT_REF = "{first}"\nLITERT_REF = "{last}"\n', "v0.18.1"), needs) - - def test_qualification_workflow_uses_exact_stable_candidate(self): - workflow = (REPO / ".github/workflows/pr_release_qualification.yml").read_text() - self.assertIn("QUALIFICATION_UPSTREAM_TAG: v0.20.0", workflow) - self.assertIn("QUALIFICATION_UPSTREAM_COMMIT: 95df4c2a932b4917ace66fcfef6c154e8d2a6699", workflow) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_v019_decisions.py b/tools/test_v019_decisions.py deleted file mode 100644 index 6fce57e..0000000 --- a/tools/test_v019_decisions.py +++ /dev/null @@ -1,170 +0,0 @@ -from __future__ import annotations - -import tempfile -import unittest -from pathlib import Path - -from android_gpu_safety_patch import applies as android_gpu_safety_applies -from asr_litertlm_container_patch import require_container_patch_decision -from asr_overlap_patch import V019_MERGER_SOURCE, source_patch_manifest -from litert_cpu_options_identifier_patch import require_cpu_options_identifier_patch_decision -from ios_runtime_policy import verify_upstream_fst_gate -from litert_lm_symbols import ( - APPLE_STATIC_GPU_ACCELERATOR_SYMBOLS, - has_prebuilt_apple_litert_companions, - has_prebuilt_apple_metal_accelerator, - has_prebuilt_topk_samplers, - required_bridge_symbols, - required_c_api_symbols, - uses_c_api_v1, -) -from package_ios_runtime import ios_dlopen_dependencies -from package_ios_runtime import validate_source_built_symbols as ios_source_built_symbols -from package_macos_runtime import validate_source_built_symbols as macos_source_built_symbols -from prebuilt_overrides import prebuilt_overrides -from stream_finish_reason_patch import require_finish_reason_patch_decision -from validate_release_manifest import allowed_spm_assets, required_spm_assets -from validate_runtime_artifacts import forbidden_runtime_artifacts, required_runtime_artifacts -from validate_runtime_dependencies import newest_glibc_requirement -from workspace_build_patch import require_workspace_build_patch_decision -from xnnpack_pf32_sme2_patch import commit_for as xnnpack_commit_for - - -class V019DecisionsTest(unittest.TestCase): - def test_upstream_contained_carries_are_retired(self) -> None: - self.assertFalse(require_container_patch_decision("v0.19.0")) - self.assertFalse(require_cpu_options_identifier_patch_decision("v0.19.0")) - self.assertFalse(require_workspace_build_patch_decision("v0.19.0")) - - def test_manifest_records_only_the_carries_still_applied(self) -> None: - records = source_patch_manifest("v0.19.0") - self.assertEqual( - {record["id"] for record in records}, - {"asr-untimed-overlap", "stream-finish-reason", - "xnnpack-pf32-sme2", "xnnpack-pqs8-qc4w-sme2", - "android-qwen3-gpu-safety", "huggingface-token-bytes"}, - ) - overlap = next(r for r in records if r["id"] == "asr-untimed-overlap") - self.assertEqual(overlap["source"], V019_MERGER_SOURCE) - self.assertTrue(require_finish_reason_patch_decision("v0.19.0")) - - def test_topk_sampler_packaging_stops_at_v019(self) -> None: - self.assertTrue(has_prebuilt_topk_samplers("v0.18.1")) - self.assertFalse(has_prebuilt_topk_samplers("v0.19.0")) - self.assertTrue(uses_c_api_v1("v0.19.0")) - self.assertFalse(uses_c_api_v1("v0.18.1")) - self.assertIn("libLiteRtTopKMetalSampler.dylib", - ios_dlopen_dependencies("v0.18.1")) - self.assertEqual(ios_dlopen_dependencies("v0.19.0"), ()) - for assets in (required_spm_assets("v0.19.0"), allowed_spm_assets("v0.19.0")): - self.assertFalse([name for name in assets if "TopK" in name]) - self.assertTrue([name for name in required_spm_assets("v0.18.1") if "TopK" in name]) - self.assertFalse([path for path in required_runtime_artifacts("v0.19.0") if "TopK" in str(path)]) - - def test_apple_metal_accelerator_packaging_stops_at_v019(self) -> None: - metal_zip = "litert-lm-native-apple-LiteRtMetalAccelerator-xcframework-{tag}.zip" - self.assertTrue(has_prebuilt_apple_metal_accelerator("v0.18.1")) - self.assertFalse(has_prebuilt_apple_metal_accelerator("v0.19.1")) - self.assertIn("libLiteRtMetalAccelerator.dylib", ios_dlopen_dependencies("v0.18.1")) - self.assertIn(metal_zip, required_spm_assets("v0.18.1")) - self.assertNotIn(metal_zip, allowed_spm_assets("v0.19.1")) - self.assertTrue([p for p in required_runtime_artifacts("v0.18.1") if "Metal" in str(p)]) - self.assertFalse([p for p in required_runtime_artifacts("v0.19.1") if "Metal" in str(p)]) - self.assertEqual(forbidden_runtime_artifacts("v0.18.1"), []) - self.assertEqual( - {p.as_posix() for p in forbidden_runtime_artifacts("v0.19.1") if "Metal" in p.name}, - { - "bin/ios/arm64/LiteRtMetalAccelerator.framework/LiteRtMetalAccelerator", - "bin/ios/arm64-sim/LiteRtMetalAccelerator.framework/LiteRtMetalAccelerator", - "bin/ios/arm64/libLiteRtMetalAccelerator.dylib", - "bin/ios/arm64-sim/libLiteRtMetalAccelerator.dylib", - "bin/macos/arm64/libLiteRtMetalAccelerator.dylib", - }, - ) - - def test_apple_litert_companion_packaging_stops_at_v019(self) -> None: - litert_zips = { - "litert-lm-native-apple-LiteRt-xcframework-{tag}.zip", - "litert-lm-native-apple-LiteRtWebGpuAccelerator-xcframework-{tag}.zip", - } - self.assertTrue(has_prebuilt_apple_litert_companions("v0.18.1")) - self.assertFalse(has_prebuilt_apple_litert_companions("v0.19.1")) - self.assertTrue(litert_zips <= set(allowed_spm_assets("v0.18.1"))) - self.assertFalse(litert_zips & set(allowed_spm_assets("v0.19.1"))) - self.assertFalse(litert_zips & set(required_spm_assets("v0.19.1"))) - self.assertEqual(forbidden_runtime_artifacts("v0.18.1"), []) - self.assertLessEqual( - { - "bin/ios/arm64/libLiteRt.dylib", - "bin/ios/arm64-sim/libLiteRt.dylib", - "bin/macos/arm64/libLiteRt.dylib", - "bin/macos/arm64/libLiteRtWebGpuAccelerator.dylib", - }, - {p.as_posix() for p in forbidden_runtime_artifacts("v0.19.1")}, - ) - - def test_v019_apple_runtimes_require_a_static_gpu_accelerator(self) -> None: - required = (required_c_api_symbols("v0.19.1") - + required_bridge_symbols("v0.19.1")) - for platform, validate in (("ios", ios_source_built_symbols), - ("macos", macos_source_built_symbols)): - static = APPLE_STATIC_GPU_ACCELERATOR_SYMBOLS[platform] - with self.subTest(platform=platform), tempfile.TemporaryDirectory() as temp: - binary = Path(temp) / "LiteRtLm" - binary.write_bytes(b"\0".join(required)) - with self.assertRaisesRegex(RuntimeError, static.decode()): - validate(binary, "v0.19.1") - validate(binary, "v0.18.1") - binary.write_bytes(b"\0".join([*required, static])) - validate(binary, "v0.19.1") - - def test_ios_fst_gate_follows_the_build_config_layout(self) -> None: - provider = '"//runtime/components/constrained_decoding:gemma_model_constraint_provider_lib",\n' - processors = ( - 'actual = "//build_config:disable_fst_constraints"\n' - '":litert_lm_fst_constraints_disabled": [\n"x",\n],\n' - '"//conditions:default": [\n' + provider + '],\n' - ) - define = 'define_values = {"LITERT_LM_FST_CONSTRAINTS_DISABLED": "1"},\n' - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - (root / "build_config").mkdir() - directory = root / "runtime/conversation/model_data_processor" - directory.mkdir(parents=True) - (root / "build_config/BUILD").write_text(define) - (directory / "BUILD").write_text(processors) - verify_upstream_fst_gate(root) - (directory / "BUILD").write_text(processors + provider) - with self.assertRaisesRegex(RuntimeError, "dependency gate"): - verify_upstream_fst_gate(root) - (root / "build_config/BUILD").write_text("") - with self.assertRaisesRegex(RuntimeError, "disable gate"): - verify_upstream_fst_gate(root) - - def test_newest_glibc_requirement_compares_numerically(self) -> None: - with tempfile.TemporaryDirectory() as temp: - library = Path(temp) / "lib.so" - library.write_bytes(b"\0GLIBC_2.9\0GLIBC_2.39\0GLIBC_2.2.5\0") - self.assertEqual(newest_glibc_requirement(library), (2, 39)) - library.write_bytes(b"\0") - self.assertIsNone(newest_glibc_requirement(library)) - - def test_android_dawn_rollback_waits_for_device_evidence(self) -> None: - self.assertEqual(prebuilt_overrides("v0.19.0"), prebuilt_overrides("v0.18.1")) - - def test_v0191_keeps_v0190_carries_and_adds_gpu_staging_and_step_zero(self) -> None: - records = source_patch_manifest("v0.19.1") - v0190 = source_patch_manifest("v0.19.0") - self.assertEqual(records[:len(v0190)], v0190) - self.assertEqual([record["id"] for record in records[len(v0190):]], - ["step-zero-state"] + ["litert-stage-spatial-tensors"] * 4) - self.assertEqual(prebuilt_overrides("v0.19.1"), prebuilt_overrides("v0.19.0")) - self.assertEqual(xnnpack_commit_for("v0.19.1"), xnnpack_commit_for("v0.19.0")) - self.assertTrue(android_gpu_safety_applies("v0.19.1")) - self.assertFalse(require_container_patch_decision("v0.19.1")) - self.assertFalse(require_cpu_options_identifier_patch_decision("v0.19.1")) - self.assertFalse(require_workspace_build_patch_decision("v0.19.1")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_v020_decisions.py b/tools/test_v020_decisions.py index 5648be6..1cdec23 100644 --- a/tools/test_v020_decisions.py +++ b/tools/test_v020_decisions.py @@ -7,11 +7,10 @@ from unittest.mock import patch import android_gpu_safety_patch -import stream_finish_reason_patch +import build_upstream_runtime as build from asr_overlap_patch import source_patch_manifest, source_sha256 -from build_upstream_runtime import patch_stream_finish_reason from prebuilt_overrides import prebuilt_overrides -from xnnpack_pf32_sme2_patch import commit_for +from xnnpack_pf32_sme2_patch import XNNPACK_COMMIT class V020DecisionsTest(unittest.TestCase): @@ -20,10 +19,10 @@ def test_git_format_carries_apply_inside_owner_checkout(self) -> None: after = b"context\npatched\n" hashes = source_sha256(before), source_sha256(after) names_and_appliers = ( - (stream_finish_reason_patch, "c/c_api_internal.h", patch_stream_finish_reason, - {"V020_SOURCES": {"c/c_api_internal.h": hashes}}), + (build, "c/c_api_internal.h", build.patch_stream_finish_reason, + {"FINISH_REASON_SOURCES": {"c/c_api_internal.h": hashes}}), (android_gpu_safety_patch, "c/engine.cc", android_gpu_safety_patch.apply, - {"V020_SOURCES": {"c/engine.cc": hashes}}), + {"SOURCES": {"c/engine.cc": hashes}}), ) with tempfile.TemporaryDirectory() as temp: owner = Path(temp) @@ -40,7 +39,8 @@ def test_git_format_carries_apply_inside_owner_checkout(self) -> None: f"--- a/{name}\n+++ b/{name}\n" "@@ -1,2 +1,2 @@\n context\n-upstream\n+patched\n" ).encode()) - with patch.multiple(module, V020_PATCH_PATH=str(patch_file), **identities): + patch_attr = "FINISH_REASON_PATCH_PATH" if module is build else "PATCH_PATH" + with patch.multiple(module, **{patch_attr: str(patch_file)}, **identities): apply(source_root, "v0.20.0") self.assertEqual(source.read_bytes(), after) self.assertFalse((owner / name).exists()) @@ -48,8 +48,12 @@ def test_git_format_carries_apply_inside_owner_checkout(self) -> None: def test_manifest_keeps_audited_carries_with_new_source_identities(self) -> None: previous = source_patch_manifest("v0.19.1") records = source_patch_manifest("v0.20.0") - self.assertEqual({r["id"] for r in records}, ({r["id"] for r in previous} - {"step-zero-state"}) | {"windows-engine-fd"}) - self.assertEqual(len(records), len(previous) + 1) + self.assertEqual(previous, []) + self.assertEqual({r["id"] for r in records}, { + "asr-untimed-overlap", "stream-finish-reason", "android-qwen3-gpu-safety", + "windows-engine-fd", "xnnpack-pf32-sme2", "xnnpack-pqs8-qc4w-sme2", + "huggingface-token-bytes", "litert-stage-spatial-tensors", + }) self.assertEqual(len({(r["id"], r["source"]) for r in records}), len(records)) by_id = {r["id"]: r for r in records} for patch_id in ( @@ -60,7 +64,7 @@ def test_manifest_keeps_audited_carries_with_new_source_identities(self) -> None self.assertEqual( by_id["asr-untimed-overlap"]["path"], "native/bridge/asr_untimed_overlap_v019.patch", ) - self.assertEqual(commit_for("v0.20.0"), "08cc38b61f7589f84e91c6e343e0f130ae3279ca") - self.assertEqual(prebuilt_overrides("v0.20.0"), prebuilt_overrides("v0.19.1")) + self.assertEqual(XNNPACK_COMMIT, "08cc38b61f7589f84e91c6e343e0f130ae3279ca") + self.assertEqual(prebuilt_overrides("v0.19.1"), ()) with self.assertRaisesRegex(RuntimeError, "no explicit decision"): source_patch_manifest("v0.20.1") diff --git a/tools/test_validate_release_manifest.py b/tools/test_validate_release_manifest.py index 9f0a454..3033e8a 100644 --- a/tools/test_validate_release_manifest.py +++ b/tools/test_validate_release_manifest.py @@ -88,39 +88,11 @@ def development_manifest(self) -> tuple[dict, str]: def test_owner_generated_manifest_satisfies_final_contract(self) -> None: self.validate(deepcopy(self.valid)) - def test_v0181_manifest_may_carry_source_patches(self) -> None: - from asr_overlap_patch import source_patch_manifest - - manifest = deepcopy(self.valid) - manifest["upstream"]["compatibilityTag"] = "v0.18.1" - manifest["upstream"]["sourcePatches"] = source_patch_manifest("v0.18.1") - with self.assertRaises(SystemExit) as raised: - validate_schema_2_payload( - manifest, - upstream_tag="v0.18.1", - upstream_commit=UPSTREAM_COMMIT, - compatibility_tag="v0.18.1", - native_commit=NATIVE_COMMIT, - release_tag="v0.18.1-3", - ) - self.assertNotIn("keys do not match", str(raised.exception)) - - def test_source_patches_are_rejected_where_no_patch_is_audited(self) -> None: + def test_legacy_fixture_rejects_unexpected_source_patch_records(self) -> None: manifest = deepcopy(self.valid) manifest["upstream"]["sourcePatches"] = [{"id": "unaudited"}] with self.assertRaisesRegex(SystemExit, "keys do not match"): self.validate(manifest) - manifest = deepcopy(self.valid) - manifest["upstream"]["compatibilityTag"] = "v0.18.2" - with self.assertRaisesRegex(RuntimeError, "no explicit decision"): - validate_schema_2_payload( - manifest, - upstream_tag="v0.18.2", - upstream_commit=UPSTREAM_COMMIT, - compatibility_tag="v0.18.2", - native_commit=NATIVE_COMMIT, - release_tag="v0.18.2-3", - ) def test_development_manifest_excludes_official_upstream_artifacts(self) -> None: development, release_tag = self.development_manifest() diff --git a/tools/test_workspace_build_patch.py b/tools/test_workspace_build_patch.py deleted file mode 100644 index 6466810..0000000 --- a/tools/test_workspace_build_patch.py +++ /dev/null @@ -1,130 +0,0 @@ -from __future__ import annotations - -import io -import re -import tarfile -import tempfile -import unittest -from pathlib import Path -from unittest.mock import patch - -import build_upstream_runtime as build -from asr_overlap_patch import source_patch_manifest, source_sha256 -from workspace_build_patch import ( - PATCH_PATH, - SOURCES, - require_workspace_build_patch_decision, - workspace_build_patch_manifest, -) - -REPO = Path(__file__).resolve().parents[1] -PATCH = (REPO / PATCH_PATH).read_text(encoding="utf-8") -FIXTURES = { - "WORKSPACE": "litert_lm_v0.18.1_WORKSPACE", - ".bazelrc": "litert_lm_v0.18.1.bazelrc", -} - - -def stage_v0181(root: Path) -> None: - for source, fixture in FIXTURES.items(): - (root / source).write_bytes((REPO / "tools/fixtures" / fixture).read_bytes()) - - -class WorkspaceBuildPatchTest(unittest.TestCase): - def test_decision_applies_only_to_v0181(self) -> None: - for tag in ("v0.17.1", "v0.18.0"): - self.assertFalse(require_workspace_build_patch_decision(tag)) - self.assertEqual(workspace_build_patch_manifest(tag), []) - self.assertTrue(require_workspace_build_patch_decision("v0.18.1")) - for tag in ("v0.18.2", "v0.19.2", "main"): - with self.subTest(tag=tag), self.assertRaisesRegex( - RuntimeError, "no explicit decision" - ): - require_workspace_build_patch_decision(tag) - - def test_patch_is_plain_and_touches_exactly_the_pinned_files(self) -> None: - targets = re.findall(r"^\+\+\+ b/(\S+)$", PATCH, re.MULTILINE) - self.assertEqual(sorted(targets), sorted(SOURCES)) - self.assertEqual(re.findall(r"^--- a/(\S+)$", PATCH, re.MULTILINE), targets) - self.assertNotRegex(PATCH, r"(?m)^(diff --git|index )") - - def test_fixtures_are_the_audited_preimages(self) -> None: - for source, fixture in FIXTURES.items(): - digest = source_sha256((REPO / "tools/fixtures" / fixture).read_bytes()) - self.assertEqual(digest, SOURCES[source][0]) - - def test_repair_loads_compatibility_proxy_and_keeps_effective_pins(self) -> None: - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - stage_v0181(root) - before = (root / "WORKSPACE").read_text(encoding="utf-8") - build.patch_workspace_build(root, "v0.18.1") - after = (root / "WORKSPACE").read_text(encoding="utf-8") - for source, (_, post) in SOURCES.items(): - self.assertEqual(source_sha256((root / source).read_bytes()), post) - for name in ("LITERT_REF", "LITERT_SHA256", "TENSORFLOW_REF", "TENSORFLOW_SHA256"): - pattern = rf'^{name} = "([0-9a-f]+)"$' - self.assertEqual(re.findall(pattern, after, re.MULTILINE), - re.findall(pattern, before, re.MULTILINE)[-1:]) - self.assertIn('load("@rules_cc//cc:extensions.bzl", "compatibility_proxy_repo")', after) - self.assertLess(after.index("tf_workspace3()"), after.index("compatibility_proxy_repo()")) - self.assertLess(after.index("compatibility_proxy_repo()"), after.index("go_rules_dependencies()")) - self.assertIn("build:windows --define=xnn_enable_avx512bf16=false", - (root / ".bazelrc").read_text(encoding="utf-8")) - # The owner WORKSPACE edits still find their anchors afterwards. - self.assertFalse(build.needs_gpu_environment_teardown_patch(after, "v0.18.1")) - build.patch_upstream_workspace(root, patch_bpe_null_piece=True) - - def test_repair_fails_closed_on_drift_and_reapplication(self) -> None: - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - stage_v0181(root) - build.patch_workspace_build(root, "v0.18.1") - with self.assertRaisesRegex(RuntimeError, "requalify the WORKSPACE build repair"): - build.patch_workspace_build(root, "v0.18.1") - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - stage_v0181(root) - with (root / ".bazelrc").open("a", encoding="utf-8") as bazelrc: - bazelrc.write("# drift\n") - with self.assertRaisesRegex(RuntimeError, "requalify the WORKSPACE build repair"): - build.patch_workspace_build(root, "v0.18.1") - build.patch_workspace_build(Path("missing"), "v0.18.0") - - def test_repair_fails_when_the_applied_postimage_is_wrong(self) -> None: - wrong = {name: (pre, "0" * 64) for name, (pre, _) in SOURCES.items()} - with tempfile.TemporaryDirectory() as temp, \ - patch.object(build, "WORKSPACE_BUILD_PATCH_SOURCES", wrong): - root = Path(temp) - stage_v0181(root) - with self.assertRaisesRegex(RuntimeError, "postimage mismatch"): - build.patch_workspace_build(root, "v0.18.1") - - def test_download_repairs_workspace_before_owner_workspace_edits(self) -> None: - def fake_download(_url, path, **_kwargs): - with tarfile.open(path, "w:gz") as archive: - for source, fixture in FIXTURES.items(): - data = (REPO / "tools/fixtures" / fixture).read_bytes() - info = tarfile.TarInfo(f"LiteRT-LM-v0.18.1/{source}") - info.size = len(data) - archive.addfile(info, io.BytesIO(data)) - - with tempfile.TemporaryDirectory() as temp, \ - patch.object(build, "download_to_path", side_effect=fake_download): - root = build.download_upstream("v0.18.1", "v0.18.1", Path(temp)) - self.assertEqual(source_sha256((root / ".bazelrc").read_bytes()), SOURCES[".bazelrc"][1]) - workspace = (root / "WORKSPACE").read_text(encoding="utf-8") - self.assertIn("compatibility_proxy_repo()", workspace) - self.assertIn("@//bridge:sentencepiece_bpe_null.patch", workspace) - - def test_manifest_records_both_files_after_the_other_carries(self) -> None: - records = [r for r in source_patch_manifest("v0.18.1") - if r["id"] not in {"xnnpack-pf32-sme2", "xnnpack-pqs8-qc4w-sme2", - "litert-cpu-options-identifier"}] - self.assertEqual(records[-2:], workspace_build_patch_manifest("v0.18.1")) - self.assertEqual([record["source"] for record in records[-2:]], list(SOURCES)) - self.assertNotIn("workspace-build", {r["id"] for r in source_patch_manifest("v0.18.0")}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_xnnpack_pf32_sme2_patch.py b/tools/test_xnnpack_pf32_sme2_patch.py index 7be0edd..c5971d3 100644 --- a/tools/test_xnnpack_pf32_sme2_patch.py +++ b/tools/test_xnnpack_pf32_sme2_patch.py @@ -1,17 +1,14 @@ from __future__ import annotations import hashlib -import io import re -import tarfile import tempfile import unittest from pathlib import Path -from unittest.mock import MagicMock, patch +from unittest.mock import patch import build_upstream_runtime as build from asr_overlap_patch import source_patch_manifest -from test_workspace_build_patch import FIXTURES, stage_v0181 from xnnpack_pf32_sme2_patch import ( ARCHIVE, PATCH_PATH, @@ -20,7 +17,6 @@ XNNPACK_COMMIT, XNNPACK_SHA256, declare_patched_xnnpack, - require_xnnpack_pf32_patch_decision, xnnpack_pf32_patch_manifest, ) @@ -29,26 +25,15 @@ TF_ARCHIVE = 'http_archive(\n name = "org_tensorflow",\n' -def repaired_v0181_workspace() -> str: - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - stage_v0181(root) - build.patch_workspace_build(root, "v0.18.1") - return (root / "WORKSPACE").read_text(encoding="utf-8") +WORKSPACE = ( + 'load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")\n' + f'TENSORFLOW_REF = "{TENSORFLOW_REF}"\n' + '# TensorFlow\n' + TF_ARCHIVE + ')\ntf_workspace2()\n' +) -class XnnpackPf32Sme2PatchTest(unittest.TestCase): - def test_decision_applies_only_to_v0181(self) -> None: - for tag in ("v0.17.1", "v0.18.0"): - self.assertFalse(require_xnnpack_pf32_patch_decision(tag)) - self.assertEqual(xnnpack_pf32_patch_manifest(tag), []) - self.assertTrue(require_xnnpack_pf32_patch_decision("v0.18.1")) - for tag in ("v0.18.2", "v0.19.2", "main"): - with self.subTest(tag=tag), self.assertRaisesRegex( - RuntimeError, "no explicit decision" - ): - require_xnnpack_pf32_patch_decision(tag) +class XnnpackPf32Sme2PatchTest(unittest.TestCase): def test_patch_restores_only_the_previous_pf32_sme2_kernels(self) -> None: files = re.findall(r"^diff --git a/(\S+) b/\1$", PATCH, re.MULTILINE) self.assertEqual(files, list(SOURCES)) @@ -81,7 +66,7 @@ def changed(section: str, sign: str) -> list[str]: self.assertNotIn("Copyright", added + removed) def test_workspace_declares_the_tensorflow_pinned_xnnpack_before_tensorflow(self) -> None: - workspace = repaired_v0181_workspace() + workspace = WORKSPACE patched = declare_patched_xnnpack(workspace) self.assertEqual(declare_patched_xnnpack(patched), patched) self.assertEqual(patched.replace(ARCHIVE, "", 1), workspace) @@ -99,7 +84,7 @@ def test_workspace_declares_the_tensorflow_pinned_xnnpack_before_tensorflow(self (REPO / "native/bridge/BUILD.bazel").read_text(encoding="utf-8")) def test_workspace_declaration_fails_closed(self) -> None: - workspace = repaired_v0181_workspace() + workspace = WORKSPACE moved = workspace.replace(TENSORFLOW_REF, "0" * 40) existing = workspace.replace(TF_ARCHIVE, 'http_archive(\n name = "XNNPACK",\n)\n' + TF_ARCHIVE) missing = workspace.replace("# TensorFlow\n", "") @@ -109,32 +94,6 @@ def test_workspace_declaration_fails_closed(self) -> None: with self.subTest(message=message), self.assertRaisesRegex(RuntimeError, message): declare_patched_xnnpack(text) - def test_download_declares_xnnpack_only_for_v0181(self) -> None: - def fake_download(_url, path, **_kwargs): - with tarfile.open(path, "w:gz") as archive: - for source, fixture in FIXTURES.items(): - data = (REPO / "tools/fixtures" / fixture).read_bytes() - info = tarfile.TarInfo(f"LiteRT-LM-v0.18.1/{source}") - info.size = len(data) - archive.addfile(info, io.BytesIO(data)) - - with tempfile.TemporaryDirectory() as temp, \ - patch.object(build, "download_to_path", side_effect=fake_download): - root = build.download_upstream("v0.18.1", "v0.18.1", Path(temp)) - self.assertIn(ARCHIVE, (root / "WORKSPACE").read_text(encoding="utf-8")) - for tag, enabled in (("v0.18.0", False), ("v0.18.1", True)): - with self.subTest(tag=tag), tempfile.TemporaryDirectory() as temp: - source = Path(temp) / "source" - source.mkdir() - (source / "WORKSPACE").write_text("", encoding="utf-8") - with patch.object(build, "download_to_path"), \ - patch.object(build.tarfile, "open"), \ - patch.object(build, "patch_workspace_build"), \ - patch.object(build, "needs_gpu_environment_teardown_patch", return_value=False), \ - patch.object(build, "patch_upstream_workspace") as apply: - build.download_upstream(tag, tag, Path(temp)) - self.assertEqual(apply.call_args.kwargs["patch_xnnpack_pf32_sme2"], enabled) - def test_postimage_check_reads_every_source_in_the_bazel_external_repository(self) -> None: with tempfile.TemporaryDirectory() as temp: output_base = Path(temp) @@ -146,41 +105,19 @@ def test_postimage_check_reads_every_source_in_the_bazel_external_repository(sel fake = {name: postimage for name, (_, postimage) in fake.items()} with patch.object(build, "xnnpack_postimages", return_value=fake): with self.assertRaisesRegex(RuntimeError, "postimage mismatch"): - build.verify_xnnpack_postimages(source_root, "v0.18.1") + build.verify_xnnpack_postimages(source_root) for name in fake: (repository / name).parent.mkdir(parents=True, exist_ok=True) (repository / name).write_bytes(b"patched\r\n") - build.verify_xnnpack_postimages(source_root, "v0.18.1") + build.verify_xnnpack_postimages(source_root) (repository / "b/c.c").write_bytes(b"unpatched\n") with self.assertRaisesRegex(RuntimeError, "postimage mismatch"): - build.verify_xnnpack_postimages(source_root, "v0.18.1") - - def test_build_checks_the_postimage_after_bazel_only_for_v0181(self) -> None: - for tag, checked in (("v0.18.0", False), ("v0.18.1", True)): - calls = MagicMock() - with self.subTest(tag=tag), tempfile.TemporaryDirectory() as temp, \ - patch.object(build, "verify_carried_dependency_pins"), \ - patch.object(build, "fetch_audited_archives"), \ - patch.object(build, "patch_asr_untimed_overlap"), \ - patch.object(build, "patch_asr_litertlm_container"), \ - patch.object(build, "patch_stream_finish_reason"), \ - patch.object(build, "materialize_git_lfs_libraries", return_value=0), \ - patch.object(build, "bazel_command", return_value=["bazel"]), \ - patch.object(build, "run", calls.run), \ - patch.object(build, "verify_xnnpack_postimages", calls.verify), \ - patch.object(build, "verify_cpu_options_identifier_postimage"): - root = Path(temp) - with self.assertRaisesRegex(RuntimeError, "Expected build output missing"): - build.build_runtime(root, "macos", "arm64", tag, "2") - names = [name for name, _, _ in calls.mock_calls] - self.assertEqual(names, ["run", "verify"] if checked else ["run"]) - if checked: - calls.verify.assert_called_once_with(root, tag) + build.verify_xnnpack_postimages(source_root) def test_manifest_records_each_xnnpack_source_before_the_qc4w_opt_out(self) -> None: - records = [r for r in source_patch_manifest("v0.18.1") - if r["id"] not in {"xnnpack-pqs8-qc4w-sme2", "litert-cpu-options-identifier"}] - self.assertEqual(records[-len(SOURCES):], xnnpack_pf32_patch_manifest("v0.18.1")) + records = [r for r in source_patch_manifest("v0.20.0") + if r["id"] == "xnnpack-pf32-sme2"] + self.assertEqual(records[-len(SOURCES):], xnnpack_pf32_patch_manifest("v0.20.0")) patch_sha256 = hashlib.sha256((REPO / PATCH_PATH).read_bytes()).hexdigest() for record, (source, hashes) in zip(records[-len(SOURCES):], SOURCES.items()): self.assertEqual(record["id"], "xnnpack-pf32-sme2") diff --git a/tools/test_xnnpack_pqs8_qc4w_sme2_patch.py b/tools/test_xnnpack_pqs8_qc4w_sme2_patch.py index 12a94c3..fe88914 100644 --- a/tools/test_xnnpack_pqs8_qc4w_sme2_patch.py +++ b/tools/test_xnnpack_pqs8_qc4w_sme2_patch.py @@ -15,7 +15,6 @@ from xnnpack_pqs8_qc4w_sme2_patch import ( PATCH_PATH, SOURCES, - require_xnnpack_qc4w_patch_decision, xnnpack_qc4w_patch_manifest, ) @@ -26,17 +25,6 @@ class XnnpackPqs8Qc4wSme2PatchTest(unittest.TestCase): - def test_decision_applies_only_to_v0181(self) -> None: - for tag in ("v0.17.1", "v0.18.0"): - self.assertFalse(require_xnnpack_qc4w_patch_decision(tag)) - self.assertEqual(xnnpack_qc4w_patch_manifest(tag), []) - self.assertTrue(require_xnnpack_qc4w_patch_decision("v0.18.1")) - for tag in ("v0.18.2", "v0.19.2", "main"): - with self.subTest(tag=tag), self.assertRaisesRegex( - RuntimeError, "no explicit decision" - ): - require_xnnpack_qc4w_patch_decision(tag) - def test_patch_disables_only_the_sme2_pqs8_qc4w_config(self) -> None: self.assertEqual(re.findall(r"^diff --git a/(\S+) b/\1$", PATCH, re.MULTILINE), [CONFIG]) self.assertEqual(list(SOURCES), [CONFIG]) @@ -60,12 +48,12 @@ def test_patch_applies_after_the_pf32_rollback(self) -> None: def test_build_verifies_the_final_postimage_of_every_patched_source(self) -> None: expected = {name: postimage for name, (_, postimage) in PF32_SOURCES.items()} expected[CONFIG] = SOURCES[CONFIG][1] - self.assertEqual(build.xnnpack_postimages("v0.18.1"), expected) + self.assertEqual(build.xnnpack_postimages(), expected) def test_manifest_records_the_opt_out_last(self) -> None: - records = [r for r in source_patch_manifest("v0.18.1") - if r["id"] != "litert-cpu-options-identifier"] - self.assertEqual(records[-1:], xnnpack_qc4w_patch_manifest("v0.18.1")) + records = [r for r in source_patch_manifest("v0.20.0") + if r["id"].startswith("xnnpack-")] + self.assertEqual(records[-1:], xnnpack_qc4w_patch_manifest("v0.20.0")) record = records[-1] self.assertEqual(record["id"], "xnnpack-pqs8-qc4w-sme2") self.assertEqual(record["path"], PATCH_PATH) diff --git a/tools/windows_engine_fd_patch.py b/tools/windows_engine_fd_patch.py index e181311..873e6cc 100644 --- a/tools/windows_engine_fd_patch.py +++ b/tools/windows_engine_fd_patch.py @@ -1,34 +1,24 @@ """Pin the MSVC-compatible engine-settings file descriptor source.""" import hashlib -import re from pathlib import Path -from android_gpu_safety_patch import V020_SOURCES, apply as apply_android_gpu_safety, digest -from source_patch_utils import apply_source_patch +from android_gpu_safety_patch import SOURCES, apply as apply_android_gpu_safety, digest +from source_patch_utils import active_source_carries, apply_source_patch PATCH_PATH = "native/bridge/windows_engine_fd_v020.patch" SOURCE = "c/engine.cc" -PREIMAGE_SHA256 = V020_SOURCES[SOURCE][1] +PREIMAGE_SHA256 = SOURCES[SOURCE][1] POSTIMAGE_SHA256 = "c6371431aa7d7d95a2ec0ec1a317be83efd5ae4513f14dd46c51fb0c15816b30" -def require_windows_engine_fd_patch_decision(tag: str) -> bool: - if tag == "v0.20.0": - return True - version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", tag) - if version and tuple(map(int, version.groups())) < (0, 20, 0): - return False - raise RuntimeError(f"Windows engine file descriptor patch has no explicit decision for {tag}") - - def apply(source_root: Path, tag: str) -> None: - if not require_windows_engine_fd_patch_decision(tag): + if not active_source_carries(tag): return source = source_root / SOURCE # Both patches touch engine.cc. A retry must also verify the GPU guard's BUILD edit. if digest(source) == POSTIMAGE_SHA256: - if digest(source_root / "c/BUILD") != V020_SOURCES["c/BUILD"][1]: + if digest(source_root / "c/BUILD") != SOURCES["c/BUILD"][1]: raise RuntimeError("C API BUILD source changed; requalify Android GPU preflight") return apply_android_gpu_safety(source_root, tag) @@ -41,7 +31,7 @@ def apply(source_root: Path, tag: str) -> None: def manifest(tag: str) -> list[dict]: - if not require_windows_engine_fd_patch_decision(tag): + if not active_source_carries(tag): return [] patch_file = Path(__file__).resolve().parents[1] / PATCH_PATH return [{ diff --git a/tools/workspace_build_patch.py b/tools/workspace_build_patch.py deleted file mode 100644 index 562459c..0000000 --- a/tools/workspace_build_patch.py +++ /dev/null @@ -1,59 +0,0 @@ -"""Identity of the carried v0.18.1 Bazel WORKSPACE build repair.""" -import hashlib -import re -from pathlib import Path - -PATCH_PATH = "native/bridge/v0181_workspace_build.patch" -# v0.18.1 took main's LiteRT/TensorFlow pin bump (RevId 996789227) without the -# WORKSPACE plumbing that TensorFlow a1179d3c needs, so its Bazel loading phase -# fails on `compatibility_proxy_repo`. The postimages are byte-identical to -# upstream main d99b438f, the same RevId with the same pins. -UPSTREAM_EQUIVALENT = "d99b438f0a961ac2a449d341c2431e49332c1076" -AUDITED_TAGS = frozenset({"v0.18.1"}) -# v0.19.0 and v0.19.1 descend from UPSTREAM_EQUIVALENT and declare the same -# plumbing. -UPSTREAM_FIX_TAGS = frozenset({"v0.19.0", "v0.19.1", "v0.20.0"}) -# LF-normalized (preimage, postimage) SHA-256 per patched v0.18.1 file. -SOURCES = { - ".bazelrc": ( - "0f585dc62934562993848d588018cd5fd4a4e92ff8a01e17c31a5cd63820aa77", - "b2143d38c990969a901d54055da9875142b895d64202afc5548e67a1adc3988e", - ), - "WORKSPACE": ( - "2dfa4a5a492b9b99be2e767b4573bc65f1c5268a502391755af22ca77ea0e88a", - "f251c52a03dc229cdd18fb61a1aeaf0c4a625c487fd4598087832c59726dbb66", - ), -} - - -def require_workspace_build_patch_decision(compatibility_tag: str) -> bool: - """Returns whether the repair applies; newer sources need a decision.""" - if compatibility_tag in AUDITED_TAGS: - return True - if compatibility_tag in UPSTREAM_FIX_TAGS: - return False - version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", compatibility_tag) - if version and tuple(map(int, version.groups())) <= (0, 18, 0): - return False - raise RuntimeError( - f"Bazel WORKSPACE build repair has no explicit decision for " - f"{compatibility_tag}; revalidate the carried patch or record an " - "upstream equivalent in tools/workspace_build_patch.py and " - "docs/upstream_patch_audit.md") - - -def workspace_build_patch_manifest(compatibility_tag: str) -> list[dict]: - if not require_workspace_build_patch_decision(compatibility_tag): - return [] - patch_sha256 = hashlib.sha256( - (Path(__file__).resolve().parents[1] / PATCH_PATH).read_bytes() - ).hexdigest() - return [{ - "id": "workspace-build", - "path": PATCH_PATH, - "sha256": patch_sha256, - "source": source, - "preimageSha256Lf": preimage, - "postimageSha256Lf": postimage, - "scope": "source-built runtimes only; excludes official upstream prebuilts", - } for source, (preimage, postimage) in SOURCES.items()] diff --git a/tools/xnnpack_pf32_sme2_patch.py b/tools/xnnpack_pf32_sme2_patch.py index 21c8111..f079ed9 100644 --- a/tools/xnnpack_pf32_sme2_patch.py +++ b/tools/xnnpack_pf32_sme2_patch.py @@ -3,56 +3,17 @@ import re from pathlib import Path +from source_patch_utils import active_source_carries + PATCH_PATH = "native/bridge/xnnpack_pf32_sme2.patch" -AUDITED_TAGS = frozenset({"v0.18.1", "v0.19.0", "v0.19.1", "v0.20.0"}) -# v0.18.1 pins TensorFlow a1179d3c, whose XLA pins this XNNPACK. It contains -# 70a9c5e8ac, which moved the PF32 SME2 GEMM/GEMV to KleidiAI kernels that are -# nondeterministic with more than one thread (google/XNNPACK#11789). The patch -# reverts that commit's SME2 kernel, LHS-packing and RHS-packing selection; -# v0.18.0 pins an XNNPACK from before it. +# The PF32 SME2 kernels introduced here are nondeterministic with multiple +# threads (google/XNNPACK#11789). REVERTED_COMMIT = "70a9c5e8acf90bef0c56f33a14529027585fd436" -TENSORFLOW_REF = "a1179d3c224967bd979950b823d5ce2a7e8f4c94" -XNNPACK_COMMIT = "d89ef6669a14db203b3b7935b1b3862cb63fb6df" -XNNPACK_SHA256 = "aab0ed2b3972125ca057b8e2b16127fbf68f8128ea07dd7efe56cdb92f2c1917" +TENSORFLOW_REF = "faa06da43657488c1f7479289d11d15e03a15ba1" +XNNPACK_COMMIT = "08cc38b61f7589f84e91c6e343e0f130ae3279ca" +XNNPACK_SHA256 = "1c94d80ff3069b3510e54b41a2c82729a4053724a682fcb09840af296dcaa07c" XNNPACK_URL = f"https://github.com/google/XNNPACK/archive/{XNNPACK_COMMIT}.zip" -# LF-normalized (preimage, postimage) SHA-256 per patched XNNPACK_COMMIT source. SOURCES = { - "src/configs/gemm-config.c": ( - "0967ea0d1d9aba4c0efc2bf64f2c4683201e2e34f6d7f8b1bb74aa3b93fd7fb1", - "7297696007430648a2bf3b1bbde03d9f32b7cbcbcf8a84ba79bfddd9887909e3", - ), - "src/pf32-gemm/pf32-gemm-1x32-minmax-neonsme2.c": ( - "777115eb004977880b26ec4313d94a09f73157cbc44f3196585a1497411cbcc7", - "5d9972ed94ad8382fa184ffd66709cccaf932aa2a20b91b419834ca45c04f7b8", - ), - "src/pf32-gemm/pf32-gemm-32x32-minmax-neonsme2.c": ( - "f101b386705e62f257c8c7e613474dd811d968316e968e2ff415fefe064f3abe", - "aa692a7cfbfa6c88df6185caba1938502842d92219c9fe3e728cf1a08aa95301", - ), - "src/x32-pack-lh/x32-packlh-neonsme2.c": ( - "820b6c397d740e63efb03ab23be9a0c337b147a302dbce139ddcf55b7b8216f8", - "5aa0176053653592a86ebc848261029f2494e23f9c9be25cc9923afc901345c0", - ), -} -# v0.19.0 pins TensorFlow 4f8e6d47, whose XLA pins this XNNPACK. It still -# descends from REVERTED_COMMIT and google/XNNPACK#11789 is open. v0.19.1 keeps -# the same TensorFlow pin. -V019_TAGS = frozenset({"v0.19.0", "v0.19.1"}) -V019_TENSORFLOW_REF = "4f8e6d470a7f2864a7b2af990d3ffcfc47f05c99" -V019_XNNPACK_COMMIT = "28d1fc6d908bc4d80920be989177b7eb1a4aebc8" -V019_XNNPACK_SHA256 = "b1d4ab092cd92b1241c1d14f440b5ed725530757b540fe4fb88a20b07577e8a8" -V019_SOURCES = { - **SOURCES, - "src/configs/gemm-config.c": ( - "ccbb3bde1758f9b4f69503be619e338013a04c4a818a5703c2a31c8bd04f8fc4", - "9a5263a9c4326b09522c094f2877ddff8e43881ed45b2bc10d15a71562fc1d9d", - ), -} - -V020_TENSORFLOW_REF = "faa06da43657488c1f7479289d11d15e03a15ba1" -V020_XNNPACK_COMMIT = "08cc38b61f7589f84e91c6e343e0f130ae3279ca" -V020_XNNPACK_SHA256 = "1c94d80ff3069b3510e54b41a2c82729a4053724a682fcb09840af296dcaa07c" -V020_SOURCES = { "src/configs/gemm-config.c": ( "77f6499beb82d69ca19dd9ca31a7c591b07c78863c158701b1125dcee0bb843d", "0eff752814ec351176c48461832907ab8841c81d06c330483dae1cf45d233a9c", @@ -100,57 +61,15 @@ def archive(tensorflow_ref: str, commit: str, sha256: str) -> str: ARCHIVE = archive(TENSORFLOW_REF, XNNPACK_COMMIT, XNNPACK_SHA256) -ARCHIVES = { - TENSORFLOW_REF: ARCHIVE, - V020_TENSORFLOW_REF: archive( - V020_TENSORFLOW_REF, V020_XNNPACK_COMMIT, V020_XNNPACK_SHA256 - ), - V019_TENSORFLOW_REF: archive( - V019_TENSORFLOW_REF, V019_XNNPACK_COMMIT, V019_XNNPACK_SHA256 - ), -} - - -def sources_for(compatibility_tag: str) -> dict[str, tuple[str, str]]: - if compatibility_tag == "v0.20.0": - return V020_SOURCES - return V019_SOURCES if compatibility_tag in V019_TAGS else SOURCES - - -def commit_for(compatibility_tag: str) -> str: - if compatibility_tag == "v0.20.0": - return V020_XNNPACK_COMMIT - return V019_XNNPACK_COMMIT if compatibility_tag in V019_TAGS else XNNPACK_COMMIT - - -def archive_sha256_for(compatibility_tag: str) -> str: - if compatibility_tag == "v0.20.0": - return V020_XNNPACK_SHA256 - return V019_XNNPACK_SHA256 if compatibility_tag in V019_TAGS else XNNPACK_SHA256 - - -def require_xnnpack_pf32_patch_decision(compatibility_tag: str) -> bool: - """Returns whether the rollback applies; newer sources need a decision.""" - if compatibility_tag in AUDITED_TAGS: - return True - version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", compatibility_tag) - if version and tuple(map(int, version.groups())) <= (0, 18, 0): - return False - raise RuntimeError( - f"XNNPACK PF32 SME2 rollback has no explicit decision for " - f"{compatibility_tag}; check the pinned XNNPACK against " - "google/XNNPACK#11789 and record the decision in " - "tools/xnnpack_pf32_sme2_patch.py and docs/upstream_patch_audit.md") TENSORFLOW_ARCHIVE = '# TensorFlow\nhttp_archive(\n name = "org_tensorflow",\n' def verify_patched_xnnpack_archive(workspace: str, compatibility_tag: str) -> None: - tensorflow_ref = V019_TENSORFLOW_REF if compatibility_tag in V019_TAGS else TENSORFLOW_REF - if compatibility_tag == "v0.20.0": - tensorflow_ref = V020_TENSORFLOW_REF - if (workspace.count(ARCHIVES[tensorflow_ref] + TENSORFLOW_ARCHIVE) != 1 + if not active_source_carries(compatibility_tag): + raise RuntimeError(f"XNNPACK carries are unavailable for {compatibility_tag}; use its historical release ref") + if (workspace.count(ARCHIVE + TENSORFLOW_ARCHIVE) != 1 or len(re.findall(r'^\s*name = "XNNPACK",$', workspace, re.MULTILINE)) != 1): raise RuntimeError("Unexpected XNNPACK archive in WORKSPACE; requalify the XNNPACK patches") @@ -159,20 +78,19 @@ def declare_patched_xnnpack(workspace_text: str) -> str: """Inserts the patched XNNPACK archive before the TensorFlow archive.""" refs = re.findall(r'^TENSORFLOW_REF = "([0-9a-f]{40})"$', workspace_text, re.MULTILINE) # Starlark uses the last assignment. - if not refs or refs[-1] not in ARCHIVES: + if not refs or refs[-1] != TENSORFLOW_REF: raise RuntimeError("TensorFlow pin changed; requalify the XNNPACK patches") - pinned_archive = ARCHIVES[refs[-1]] - if pinned_archive in workspace_text: + if ARCHIVE in workspace_text: return workspace_text if re.search(r'^\s*name = "XNNPACK",$', workspace_text, re.MULTILINE): raise RuntimeError("Unexpected XNNPACK archive in WORKSPACE; requalify the XNNPACK patches") if workspace_text.count(TENSORFLOW_ARCHIVE) != 1: raise RuntimeError("Expected one TensorFlow archive in WORKSPACE") - return workspace_text.replace(TENSORFLOW_ARCHIVE, pinned_archive + TENSORFLOW_ARCHIVE, 1) + return workspace_text.replace(TENSORFLOW_ARCHIVE, ARCHIVE + TENSORFLOW_ARCHIVE, 1) def xnnpack_pf32_patch_manifest(compatibility_tag: str) -> list[dict]: - if not require_xnnpack_pf32_patch_decision(compatibility_tag): + if not active_source_carries(compatibility_tag): return [] patch_sha256 = hashlib.sha256( (Path(__file__).resolve().parents[1] / PATCH_PATH).read_bytes() @@ -181,8 +99,8 @@ def xnnpack_pf32_patch_manifest(compatibility_tag: str) -> list[dict]: "id": "xnnpack-pf32-sme2", "path": PATCH_PATH, "sha256": patch_sha256, - "source": f"XNNPACK@{commit_for(compatibility_tag)}/{source}", + "source": f"XNNPACK@{XNNPACK_COMMIT}/{source}", "preimageSha256Lf": preimage, "postimageSha256Lf": postimage, "scope": "source-built runtimes only; excludes official upstream prebuilts", - } for source, (preimage, postimage) in sources_for(compatibility_tag).items()] + } for source, (preimage, postimage) in SOURCES.items()] diff --git a/tools/xnnpack_pqs8_qc4w_sme2_patch.py b/tools/xnnpack_pqs8_qc4w_sme2_patch.py index 6d64131..0aa9fc0 100644 --- a/tools/xnnpack_pqs8_qc4w_sme2_patch.py +++ b/tools/xnnpack_pqs8_qc4w_sme2_patch.py @@ -1,15 +1,9 @@ """Identity of the carried XNNPACK SME2 PQS8/QC4W GEMM opt-out (#84).""" import hashlib -import re from pathlib import Path -from xnnpack_pf32_sme2_patch import ( - AUDITED_TAGS, - SOURCES as PF32_SOURCES, - V019_SOURCES as PF32_V019_SOURCES, - V019_TAGS, - commit_for, -) +from source_patch_utils import active_source_carries +from xnnpack_pf32_sme2_patch import XNNPACK_COMMIT, SOURCES as PF32_SOURCES PATCH_PATH = "native/bridge/xnnpack_pqs8_qc4w_sme2.patch" # XNNPACK 76fa737a0 routes int8-activation, int4-weight fully connected layers @@ -23,47 +17,13 @@ SOURCES = { "src/configs/gemm-config.c": ( PF32_SOURCES["src/configs/gemm-config.c"][1], - "fb5075c9e04c562d5c6ed702f18a68117682dd85c3286c9b2e2495c6b44d3f26", - ), -} -V019_SOURCES = { - "src/configs/gemm-config.c": ( - PF32_V019_SOURCES["src/configs/gemm-config.c"][1], - "0f843f1b2ad56193aee22382a56d279c9f904534c4b9e2942e5e77585016662f", - ), -} - -V020_SOURCES = { - "src/configs/gemm-config.c": ( - "0eff752814ec351176c48461832907ab8841c81d06c330483dae1cf45d233a9c", "3bad8691babc6044975b8720fd88be0e7e420322533330f108df2901ca15110d", ), } -def sources_for(compatibility_tag: str) -> dict[str, tuple[str, str]]: - if compatibility_tag == "v0.20.0": - return V020_SOURCES - return V019_SOURCES if compatibility_tag in V019_TAGS else SOURCES - - -def require_xnnpack_qc4w_patch_decision(compatibility_tag: str) -> bool: - """Returns whether the opt-out applies; newer sources need a decision.""" - if compatibility_tag in AUDITED_TAGS: - return True - version = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", compatibility_tag) - if version and tuple(map(int, version.groups())) <= (0, 18, 0): - return False - raise RuntimeError( - f"XNNPACK PQS8/QC4W SME2 opt-out has no explicit decision for " - f"{compatibility_tag}; check the pinned XNNPACK against " - "google/XNNPACK#11793, then record the decision by adding the tag to " - "AUDITED_TAGS in tools/xnnpack_pf32_sme2_patch.py (shared with the " - "PF32 rollback, so audit both) and in docs/upstream_patch_audit.md") - - def xnnpack_qc4w_patch_manifest(compatibility_tag: str) -> list[dict]: - if not require_xnnpack_qc4w_patch_decision(compatibility_tag): + if not active_source_carries(compatibility_tag): return [] patch_sha256 = hashlib.sha256( (Path(__file__).resolve().parents[1] / PATCH_PATH).read_bytes() @@ -72,8 +32,8 @@ def xnnpack_qc4w_patch_manifest(compatibility_tag: str) -> list[dict]: "id": "xnnpack-pqs8-qc4w-sme2", "path": PATCH_PATH, "sha256": patch_sha256, - "source": f"XNNPACK@{commit_for(compatibility_tag)}/{source}", + "source": f"XNNPACK@{XNNPACK_COMMIT}/{source}", "preimageSha256Lf": preimage, "postimageSha256Lf": postimage, "scope": "source-built runtimes only; excludes official upstream prebuilts", - } for source, (preimage, postimage) in sources_for(compatibility_tag).items()] + } for source, (preimage, postimage) in SOURCES.items()] From 1d296d36bf5dbe55387d08407b7fdf53a6311c85 Mon Sep 17 00:00:00 2001 From: leehack Date: Tue, 24 Nov 2026 05:54:57 -0500 Subject: [PATCH 9/9] Reject separate LiteRT libraries in v0.20 desktop bundles --- docs/platform_strategy.md | 31 +++++++++------ tools/test_validate_runtime_dependencies.py | 42 +++++++++++++++++++++ tools/validate_runtime_dependencies.py | 19 ++++++++++ 3 files changed, 80 insertions(+), 12 deletions(-) create mode 100644 tools/test_validate_runtime_dependencies.py diff --git a/docs/platform_strategy.md b/docs/platform_strategy.md index ea5540a..87bb873 100644 --- a/docs/platform_strategy.md +++ b/docs/platform_strategy.md @@ -52,12 +52,12 @@ reaches LiteRT: | 0 | Not established. Builds before v0.19 report 0; their Linux and Windows runtimes for v0.16 to v0.18 load upstream's prebuilt `libLiteRt` (#111). | | missing | The runtime predates the marker; treat it as 0. | -The marker covers only the LiteRT-LM to LiteRT weight handoff. It is not GPU -qualification: the `gpu_registry.cc` fallback to the prebuilt accelerator still -resolves LiteRT symbols from the host, which is the -[#47](https://github.com/leehack/litert-lm-native/issues/47) crash class. On -Linux, a consumer that preloads a separate `libLiteRt` with `RTLD_GLOBAL` -recreates the #111 state while the marker still reads 1. +The marker covers the LiteRT-LM to LiteRT weight handoff. On earlier bundles with +a prebuilt accelerator, the `gpu_registry.cc` fallback can resolve LiteRT symbols +from the host, which is the +[#47](https://github.com/leehack/litert-lm-native/issues/47) crash class. On Linux, +preloading an external `libLiteRt` with `RTLD_GLOBAL` can recreate the #111 state +while the marker still reads 1. Every source build from LiteRT-LM v0.19 reports 1 on every platform. The export is additive and carries no other ABI change. It is a bridge export @@ -208,12 +208,19 @@ the weights and Windows crashed, which broke every bundle with external-weight sections, such as EmbeddingGemma-2. The build fails if a v0.19+ host on any platform still imports `libLiteRt`, and those hosts report `litert_lm_native_in_process_litert_abi_version()` 1, so consumers can refuse -external-weight bundles on older desktop runtimes. Bundles keep shipping the -upstream `libLiteRt` and `libLiteRtWebGpuAccelerator` files on Linux, Windows -and Android, but the host loads neither. Apple bundles after `v0.19.1-3` omit -the macOS `libLiteRt` and `libLiteRtWebGpuAccelerator` and the iOS loose -`libLiteRt` (`has_prebuilt_apple_litert_companions`), and so publish no -`LiteRt` or `LiteRtWebGpuAccelerator` XCFramework. +external-weight bundles on older desktop runtimes. Linux and Windows v0.19 +bundles included upstream `libLiteRt` and `libLiteRtWebGpuAccelerator` files. +Apple bundles omit those companions after `v0.19.1-3`. LiteRT-LM v0.20.0 +removed the prebuilts upstream. The package validator rejects either separate +library in a v0.20+ desktop bundle. The source-built accelerator uses the +packaged Dawn library. + +For desktop GPU qualification, record the archive SHA-256, SHA-256 of every +file in the loaded runtime directory, model SHA-256, selected GPU backend, and +driver version alongside the candidate and comparison run logs. The +[v0.19.1-2 L4 receipt](https://github.com/leehack/llamadart/pull/1830#issuecomment-6731113939) +binds the Linux Vulkan and Windows D3D12 results to that release's bundle and +loaded runtime digests. The rest of this section covers v0.16 to v0.18. diff --git a/tools/test_validate_runtime_dependencies.py b/tools/test_validate_runtime_dependencies.py new file mode 100644 index 0000000..24fd923 --- /dev/null +++ b/tools/test_validate_runtime_dependencies.py @@ -0,0 +1,42 @@ +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +import validate_runtime_dependencies as validate + + +class DesktopLiteRtBundleTest(unittest.TestCase): + def test_current_cli_rejects_separate_desktop_litert_and_accelerator(self) -> None: + cases = ( + "linux/x64/libLiteRt.so", + "linux/arm64/libLiteRtWebGpuAccelerator.so", + "macos/arm64/libLiteRtWebGpuAccelerator.dylib", + "windows/x64/libLiteRt.dll", + ) + for library in cases: + with self.subTest(library=library), tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "bin" / library + path.parent.mkdir(parents=True) + path.touch() + with patch.object(sys, "argv", [ + "validate_runtime_dependencies.py", "--root", directory, + "--upstream-tag", "v0.20.0", + ]), self.assertRaises(SystemExit) as failure: + validate.main() + self.assertIn(f"bin/{library}", str(failure.exception)) + + def test_accepts_legacy_companions_and_current_runtime_dependencies(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + runtime = root / "bin/linux/x64" + runtime.mkdir(parents=True) + companion = runtime / "libLiteRt.so" + companion.touch() + validate.validate_desktop_litert_bundle(root, "v0.19.1") + companion.unlink() + for name in ("libLiteRtLm.so", "libwebgpu_dawn.so", + "libGemmaModelConstraintProvider.so"): + (runtime / name).touch() + validate.validate_desktop_litert_bundle(root, "v0.20.0") diff --git a/tools/validate_runtime_dependencies.py b/tools/validate_runtime_dependencies.py index 9724bad..253dc1b 100644 --- a/tools/validate_runtime_dependencies.py +++ b/tools/validate_runtime_dependencies.py @@ -44,6 +44,24 @@ def fail(message: str) -> None: raise SystemExit(message) +def validate_desktop_litert_bundle(root: Path, upstream_tag: str) -> None: + if not is_at_least(upstream_tag, (0, 20, 0)): + return + companions = re.compile( + r"(?:lib)?litert(?:webgpuaccelerator)?\.(?:so(?:\.\d+)*|dylib|dll)", + re.IGNORECASE, + ) + found = sorted( + path.relative_to(root).as_posix() + for platform in ("linux", "macos", "windows") + for path in (root / "bin" / platform).glob("*/*") + if companions.fullmatch(path.name) and (path.is_file() or path.is_symlink()) + ) + if found: + fail("v0.20+ desktop runtimes must not bundle separate LiteRT or WebGPU " + "accelerator libraries:\n" + "\n".join(f"- {path}" for path in found)) + + def iter_elf_libraries(root: Path) -> list[Path]: bin_dir = root / "bin" if not bin_dir.exists(): @@ -358,6 +376,7 @@ def main() -> int: args = parser.parse_args() root = args.root.resolve() + validate_desktop_litert_bundle(root, args.upstream_tag) if provider_free_ios(args.upstream_tag): validate_ios_directory(root / "bin" / "ios") validate_ios_archives(args.archive_root or root / "dist" / "spm")