Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install litert-google-tensor@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin litert-google-tensor v1.0.0 follows the Agent Plugins spec.
gh skills-hub install litert-google-tensor Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/litert-google-tensor/ Extract the ZIP to .github/skills/ in your repo. The folder name must match litert-google-tensor for Copilot to auto-discover it.
Skill Files (21)
SKILL.md 34.9 KB
---
name: litert-google-tensor
description: >-
Compiles LiteRT (.tflite) models ahead-of-time for Google Tensor TPUs
(Tensor G5 on Pixel 10, Tensor G6 on Pixel 11) locally on Linux x86_64 or
on Google Colab (--colab on macOS, Windows, or ARM hosts),
benchmarks them on a USB-attached Pixel with LiteRT's benchmark_model
(NPU latency, peak memory, TPU tile time, TPU energy, optional CPU baseline),
and packages compiled models for an Android Gradle app as a Google Play AI
pack with the Tensor NPU runtime module and a Kotlin loader, applies it to
the app and verifies it on a Pixel. Use when the
user asks to compile, AOT-compile, or prepare a .tflite model for the Pixel
TPU/NPU, check whether a .tflite is already Tensor-compiled, measure
on-device NPU performance of a compiled model, or package or deploy a
compiled model into their Android app (or replace the one it ships). Don't
use for Qualcomm, MediaTek, or Samsung NPUs, GPU-only benchmarking,
LiteRT-LM or LLM (.litertlm) models, on-device JIT compilation, non-Gradle
builds, or publishing to Google Play.
metadata:
version: "1.0.0"
category: AiAndMachineLearning
---
# LiteRT on Google Tensor: compile, benchmark, package for apps
Three scriptable workflows for Pixel TPUs:
1. **Compile** a plain `.tflite` into a Google Tensor AOT-compiled `.tflite`
with the public LiteRT Python API (`ai_edge_litert.aot`), locally on Linux
`x86_64` or on a Google Colab VM (`--colab`, via `google-colab-cli`) when
the user is on macOS/Windows or lacks a Linux box.
2. **Benchmark** a compiled model on a connected Pixel with LiteRT's
`benchmark_model`, NPU-only, optionally next to a CPU baseline, including
TPU tile time (pure TPU compute time) and TPU energy per inference.
3. **Package** compiled builds for an Android (Gradle) app as a Google Play AI
pack with the Google Tensor NPU runtime and a Kotlin loader (or, for an app
that already ships Google Tensor builds, only the files to replace), apply
the plan to the project when the user agrees, and check the app on a Pixel.
Everything runs synchronously in the user's terminal; the scripts never start
background processes and always clean up what they pushed to the phone or
allocated on Colab. All paths below are relative to this skill's directory
(`SKILL_DIR`).
Path | Purpose
---- | -------
[assets/versions.json](assets/versions.json) | LiteRT versions the scripts use (single source)
[scripts/check_compiled.py](scripts/check_compiled.py) | Is this `.tflite` already Tensor-compiled?
[scripts/compile_model.py](scripts/compile_model.py) | AOT compile (local Linux `x86_64` or `--colab`)
[scripts/benchmark_on_device.py](scripts/benchmark_on_device.py) | adb push -> benchmark -> parse -> cleanup
[scripts/package_ai_pack.py](scripts/package_ai_pack.py) | Compiled builds -> AI pack + Gradle modules for an app, or an update of one
[scripts/install_and_verify.py](scripts/install_and_verify.py) | Build the app, install it like Google Play, read the NPU/CPU result
[assets/templates/](assets/templates/) | Gradle, Kotlin, `INTEGRATION.md` and `UPDATE.md` templates (`package_ai_pack.py`)
[references/compile-flags.md](references/compile-flags.md) | API, compiler flags, script options, `--colab`
[references/benchmark-flags.md](references/benchmark-flags.md) | What the benchmark runs, binaries, writing the report, example output
[references/app-integration.md](references/app-integration.md) | Packaging for an app: contents, checks, delivery modes, applying the plan, checking on a Pixel
[references/troubleshooting.md](references/troubleshooting.md) | Symptom -> fix tables
[references/contributing.md](references/contributing.md) | Maintainers: adopting a new LiteRT release
Every script supports `--help` and `--dry-run` and is Python 3 standard library
only, so it runs with any `python3`, with two exceptions that import LiteRT: a
local compile (`compile_model.py` without `--colab`, `--dry-run` or
`--print-install`) must use the virtualenv's interpreter
(`<venv>/bin/python SKILL_DIR/scripts/compile_model.py ...`, or activate the
venv first), and a real `package_ai_pack.py` run (not `--dry-run` or
`--check-project`) needs a Python with `ai-edge-litert` (the compile venv
works; the Beta SDK is not needed).
## Prerequisites (tell the user up front)
| Need | Compile (local) | Compile (`--colab`) | Benchmark | Package (app) |
|---|---|---|---|---|
| **Google Tensor SDK Beta access** - sign up at https://services.google.com/fb/forms/tensor_ml_sdk_experimental_access (overview: https://developers.google.com/edge/litert/next/tensor-sdk). Google emails a download link for `litert_plugin_compiler.tar.gz`; the compiler cannot be installed without it. | required | required (`--sdk-tarball` or `--sdk-url`) | - | - |
| Host OS | Linux **x86_64**, >= 16 GB RAM | any OS (`colab` CLI on PATH; runs on a remote Colab Linux `x86_64` VM) | any OS with `adb` | any OS where `ai-edge-litert` installs (the compile venv's Linux `x86_64` host works) |
| Python environment | Local venv with `ai-edge-litert` + `ai-edge-litert-sdk-google-tensor` at the version in `versions.json` (`compile_model.py --print-install`) | Any local `python3` + `google-colab-cli` (`compile_model.py --print-install --colab`); SDK is installed on the Colab VM automatically | any `python3` (stdlib only) | a Python with `ai-edge-litert` (the compile venv works; the SDK package is not needed) |
| `adb` on PATH, Pixel 10/11 with USB debugging enabled | - | - | required | step 7 (install and check the app) |
| A JDK the app's Gradle supports (`JAVA_HOME`), the Android SDK, the project's `./gradlew` | - | - | - | steps 6-7 (build, install); bundletool is downloaded once |
| `libLiteRtDispatch_GoogleTensor.so` - downloaded automatically from the public LiteRT binaries bucket (same directory as `benchmark_model`), or supplied with `--dispatch-lib` | - | - | required | - (the app gets it from Google Maven) |
| Internet | once for `pip install` | required (Colab VM + `pip install`) | once to fetch `benchmark_model` + dispatch lib (cached in `~/.cache/litert-google-tensor/`) unless supplied locally | - (the app's Gradle build downloads the LiteRT Maven artifacts) |
Supported targets: `Tensor_G5` (Pixel 10 family) and `Tensor_G6` (Pixel 11
family), as listed by the public Tensor SDK docs; Pixel 9 and older are not.
## Step 0 - Collect parameters
Ask the user only for what is missing; never invent values:
Parameter | How to get it
----------------------------------- | -------------
Model path | Absolute path to the `.tflite`. Confirm it exists.
Goal | check only, compile only, benchmark only, compile + benchmark, or package for an app (step 5). Infer it from the request ("how fast is it on the TPU vs CPU" = compile if needed + benchmark with a CPU baseline; "put it in my app" / "deploy it" = package); do not add an unrequested device run.
Target SoC | For a **compile**, the user's stated device wins (Pixel 10 family = `Tensor_G5`, Pixel 11 family = `Tensor_G6`), even if a different Pixel is attached. For a **benchmark**, the attached phone decides: `adb shell getprop ro.soc.model` -> `Tensor G5` => `Tensor_G5`, `Tensor G6` => `Tensor_G6` (the benchmark script reads and enforces this itself).
Output path | Default `<output-dir>/<stem>_Google_<target>.tflite`. `compile_model.py` refuses to overwrite an existing file (exit 2): run `check_compiled.py` on the existing file and reuse it, or pass `--output-name`, or `--overwrite` after asking. When a second build is needed next to an existing one, name it `<stem>_Google_<target>.<YYYYMMDD-HHMM>.tflite` (e.g. `--output-name model_Google_Tensor_G5.20260107-0930.tflite`) or, for a flag variant, `<stem>_Google_<target>.<flag-summary>.tflite` (`...G5.half-maxsharding.tflite`); keep the `_Google_<target>` part so the file stays recognisable.
Device serial | Only if `adb devices` lists more than one device.
Dispatch library / benchmark binary | Optional. Both are downloaded automatically from the same public bucket directory and cached. Only ask if the user wants a specific build, or if the host is offline: then `--benchmark-bin <benchmark_model>` plus `--dispatch-lib <libLiteRtDispatch_GoogleTensor.so \| dir \| .zip \| .aar>` (also env `LITERT_GOOGLE_TENSOR_DISPATCH_LIB`) use local copies and no network is touched.
CPU baseline | Optional; needs the path of the **original uncompiled** model (ask for it if only a compiled file was given; the benchmark script rejects a compiled file here with exit 2).
Run counts / mode | Defaults 5 warmup / 50 measured, `burst` performance mode. `benchmark_model` treats counts as **minimums** and also runs at least 0.5 s warmup / 1 s measured, so fast models execute more runs than requested. If the user states exact counts, say so and ask whether to disable the floors (`--extra-arg=--min_secs=0 --extra-arg=--warmup_min_secs=0`); "steady-state" / "sustained" requests map to `--performance-mode sustained_performance`.
TPU tile time | On by default, nothing to ask: a second, hooked NPU pass. `--no-tile-time` turns it off; the hooked pass itself (it repeats the NPU run, so slow models take about twice as long) is skipped only with `--no-tile-time --no-power`.
TPU energy | On by default, nothing to ask: the power metric of the same hooked pass (the TPU rail's energy per inference). `--no-power` skips it. The script leaves it off, and says why, for a dispatch library whose power hook predates the fix.
Compile mode | Local Linux `x86_64` by default. Use `--colab` when the host is not Linux `x86_64` (macOS/Windows/ARM) or when the user asks to compile on Google Colab; ask for the Beta tarball path (`--sdk-tarball` / `GOOGLE_TENSOR_SDK_BETA`) or URL (`--sdk-url` / `GOOGLE_TENSOR_ML_SDK_URL`) before running.
Compiler flags | Default to the compiler defaults; only set flags the user asks for or that troubleshooting requires (see [references/compile-flags.md](references/compile-flags.md)).
App deployment level | Packaging jobs only; nothing to ask up front. After step 5, tell the user the plan is ready (`INTEGRATION.md`, or `UPDATE.md` for an update) and ask whether you should apply it to their project (step 6). After that, offer to install the app on their Pixel and check it uses the NPU (step 7).
New integration or update | Packaging jobs only. Ask whether the app already ships Google Tensor builds (an AI pack with folders like `model#group_Google_Tensor_G5` under its `src/main/assets`). If it does, it is an **update** (step 5b): ask for the project root (the folder with `settings.gradle.kts` or `settings.gradle`). The pack, model file, device groups, delivery mode and app module then come from the project, so do not ask for them.
Builds to package | One compiled build per target SoC (`Tensor_G5`, `Tensor_G6`) plus the **original uncompiled** model they were compiled from (the app's CPU path). Compile missing targets first (step 2); a build is per SoC, so a Pixel 11 needs a `Tensor_G6` build. For an update, build every SoC the app already ships.
Delivery mode | New integrations only (an update keeps the app's). When Google Play puts the model on the phone: `install-time` (default; installed with the app, ready at first launch), `fast-follow` (downloaded right after install) or `on-demand` (downloaded when the app asks). Explain each in one sentence ([references/app-integration.md](references/app-integration.md#delivery-modes-asked-in-step-0)) and use the default when the user has no preference.
Pack / model names, app module | New integrations only. Defaults: pack name = the original's file name made valid, model name = pack name, app module `app`, Kotlin package `com.example.litert`. Ask only when the user's project differs (another app module name, their package).
Quick test (optional) | New integrations only. Offer it when the user wants to try the model on their own Pixel before setting up bundletool: `--quick-test` adds a copy of each build and the steps for `./gradlew installDebug -PtensorQuickTest=<SoC>`, which puts the build and the NPU runtime in the debug APK. Local testing only; release builds are unaffected.
## Commands or a plan only (the user says not to run anything)
Run nothing - not even the read-only scripts - and give the same steps as a
real run, in the same order, as commands the user can paste:
1. Start with `check_compiled.py` on every input model (step 1), **before**
any install or compile command; checking only the compiled output
afterwards is not enough.
2. For installs, give `python3 SKILL_DIR/scripts/compile_model.py
--print-install [--colab]` as the command that produces them (step 2a),
then the lines it prints with the user's paths filled in (venv,
`export GOOGLE_TENSOR_SDK_BETA=<their tarball>` before `pip install`) and
each version written as `<version printed by --print-install>`. Never
copy a version number from `versions.json` or from memory.
3. Give no results, not even estimates: latency, speed-up, memory and ops
offloaded come only from the scripts' output. Say where they will appear
(for a benchmark, the table `benchmark_on_device.py` prints and saves as
`report.md`).
4. When the plan changes the user's app project (step 6), say that nothing
in the project changes until they approve, and end by asking whether you
should apply it.
## Step 1 - Check whether the model is already compiled
```bash
python3 SKILL_DIR/scripts/check_compiled.py /abs/path/model.tflite [--expect-target Tensor_G5]
```
Run it on every model file involved (the model to compile or benchmark, the
CPU-baseline file, and an existing output file you are about to reuse). For a
benchmark job read the phone first (`adb shell getprop ro.soc.model` prints
`Tensor G5` or `Tensor G6`) and pass the underscore form as `--expect-target`
(`Tensor G5` -> `--expect-target Tensor_G5`), so one check answers both
"compiled?" and "for this phone?" (a plain model exits 1 either way); the
benchmark script enforces the match again anyway (exit 4).
| Exit | Meaning | Next action |
|---|---|---|
| 0 | compiled for Google Tensor (SoC printed) | skip compile; report the SoC (and the `Compile info` line if a `.compile.json` sidecar exists). Continue to step 3 only if the goal includes a benchmark. No sidecar (compiled elsewhere, flags unknown): for a plain "how fast is it" job, benchmark the file as-is and say "compile flags unknown"; when the user needs to know how it was built (or wants a reproducible comparison), compile the original with the defaults under a new `--output-name` and compare SHA-256 (`sha256sum` of both files, or `output_sha256` in the new sidecar): compilation is deterministic, so an identical hash proves the existing file is a default build ([references/compile-flags.md](references/compile-flags.md)). Never `--overwrite` to find out. |
| 1 | plain (uncompiled) model | go to step 2 if compiling; this is the correct file for `--cpu-baseline` |
| 2 | compiled for a different SoC than `--expect-target` | compiled models are SoC-specific (a `Tensor_G5` file never runs on a `Tensor_G6` TPU, and a `Tensor_G6` file never runs on a `Tensor_G5` TPU; there is no runtime fallback, and `--allow-mismatch` only produces dispatch errors). Tell the user which SoC the phone has, then offer, in this order: an existing `*_Google_<phone target>.tflite` build of the same model in the project (verify it with this check first; do not benchmark it unless the user says so), attaching the matching phone, or recompiling the **original** uncompiled export for the phone's target. |
| 3 | not a `.tflite` / missing | fix the path |
| 4 | compiled by another toolchain: an Edge TPU custom op (`edgetpu-custom-op...`) instead of LiteRT's `DISPATCH_OP` | not usable here: LiteRT cannot recompile it or run it on the Google Tensor TPU, and the CPU cannot run it (so it is no `--cpu-baseline` or `--fallback` either; the scripts refuse it). Ask for the original model it was compiled from and compile that (step 2) |
The `LiteRtStamp` is authoritative (the `_Google_Tensor_G5` suffix is only a
naming convention) and records the SoC but **not** the compiler flags: those
come from the `<model>.compile.json` sidecar that `compile_model.py` writes
next to its output; without it, say "flags unknown" rather than guessing.
## Step 2 - Compile (Linux x86_64 or Google Colab via `--colab`)
### 2a. One-time environment
The SDK pip package contains no compiler by itself: at install time it unpacks
the Beta tarball that `GOOGLE_TENSOR_SDK_BETA` points to (same flow as the
public codelab). Ask the user for the tarball path first, then print the
install commands for the LiteRT version the skill pins in `versions.json`:
```bash
python3 SKILL_DIR/scripts/compile_model.py --print-install [--colab]
```
**Local Linux `x86_64`** (`--print-install`): runs with any `python3` and prints
comment lines (the pinned version, when and on what it was last verified, the
supported Python range, and whether this host and Python qualify) followed by:
```text
python3 -m venv ~/.venvs/litert-tensor && source ~/.venvs/litert-tensor/bin/activate
pip install --upgrade pip
export GOOGLE_TENSOR_SDK_BETA=/abs/path/litert_plugin_compiler.tar.gz # from the Beta e-mail
pip install --no-cache-dir ai-edge-litert==<pinned> ai-edge-litert-sdk-google-tensor==<pinned>
```
**Remote Google Colab** (`--print-install --colab`) - for macOS, Windows,
non-x86 Linux, or when compiling on Colab without a local Linux venv: installs
`google-colab-cli` into `~/.venvs/colab-cli`
([how `--colab` works](references/compile-flags.md#compiling-on-google-colab---colab)).
Never ask the user to run a terminal command for OAuth: when `--colab` needs
one-time OAuth, show its printed URL in chat, ask the user for the code, and
re-run with `--colab-auth-code <CODE>`.
* Tell the user before installing anything. Run the printed commands with the
real tarball path and never type a LiteRT version yourself: the runtime and
SDK packages must be one version (`WARNING` when they differ; `NOTE` when
they match each other but not the pin). Use `-nightly` packages only when
the user explicitly asks for nightlies.
* If `--print-install` warns about the Python version, create the venv with
a `python3.N` in the supported range. Install errors:
[references/troubleshooting.md](references/troubleshooting.md#environment-and-install).
**If the user has no Beta access yet:** say so plainly - the compiler cannot be
installed until Google e-mails the tarball link (sign-up form above) - and do
not install anything or allocate a Colab VM meanwhile (`--colab` checks for the
tarball before `colab new`). Still useful now: run `check_compiled.py` on their
files, confirm the host and phone SoC, and run `--dry-run` / `--print-install`.
### 2b. Compile
```bash
# Local Linux x86_64 (using the virtualenv's interpreter):
python3 SKILL_DIR/scripts/compile_model.py /abs/path/model.tflite \
--target Tensor_G5 --output-dir /abs/path/compiled
# Remote Google Colab VM (any OS, any local python3 + google-colab-cli):
python3 SKILL_DIR/scripts/compile_model.py /abs/path/model.tflite \
--target Tensor_G5 --colab --sdk-tarball /abs/path/litert_plugin_compiler.tar.gz \
--output-dir /abs/path/compiled
# -> /abs/path/compiled/model_Google_Tensor_G5.tflite
```
The script prints the compilation report, re-verifies the Tensor stamp, writes
`<output>.compile.json` (flags, ops offloaded / total, package versions,
SHA-256s) and never overwrites an existing output (exit 2) unless
`--overwrite` is given. Ops left on the CPU in the report mean the strict NPU
benchmark will fail (step 3, `--allow-cpu-fallback`). Every compiler, script
and Colab option: [references/compile-flags.md](references/compile-flags.md).
* If the compiler crashes with an internal error - or the user reports that it
did with the defaults (no need to reproduce the crash) - use
`--truncation-type half --sharding-intensity maximum` (public FAQ guidance)
and tell the user which flags produced the artifact. `half` changes the
numerics (16-bit floats on the TPU), so tell the user to validate the
model's outputs against the original before relying on it.
* Report a compile-only job from the script's output and sidecar only:
```markdown
**Compiled:** <output path> (<bytes from "Compiled model written to" line>)
**Target / flags:** <cli_flags from the sidecar, or "--target X (compiler defaults)">
**Ops offloaded:** <N / M from the "Ops offloaded to the TPU" line>
**LiteRT:** <"packages" from the sidecar, plus the script's WARNING/NOTE line if it printed one>
**Verified:** check_compiled.py -> <its Status line>
```
Exit codes: 0 ok, 2 bad input, 3 already compiled, 4 unsupported host,
5 LiteRT packages or Beta compiler library missing (message includes the
install fix), 6 compile failed (compiler log errors are printed),
7 output verification failed.
## Step 3 - Benchmark on the device
```bash
python3 SKILL_DIR/scripts/benchmark_on_device.py \
--model /abs/path/compiled/model_Google_Tensor_G5.tflite \
[--cpu-baseline /abs/path/model.tflite] [--serial SERIAL] \
[--dispatch-lib /abs/path/libLiteRtDispatch_GoogleTensor.so] \
[--output-dir /abs/path/results]
```
The script refuses a model compiled for another SoC than the phone's (exit 4;
`--dry-run` never contacts the phone, so it proves nothing about the match),
fetches `benchmark_model` and `libLiteRtDispatch_GoogleTensor.so` once from the
bucket release in `versions.json` (cached; `downloaded from <url>` means a
first download - tell the user what was fetched), runs the strict NPU
benchmark, a second hooked NPU pass for TPU tile time and TPU energy, and the
optional CPU baseline on the **uncompiled** model in a fresh
`/data/local/tmp/litert_benchmark/run-*` directory, which it deletes even on
failure. It writes `report.md`, `results.json` and the logs to `--output-dir`
(nothing after exit 2/3/4 or `--dry-run`). Each step and flag:
[references/benchmark-flags.md](references/benchmark-flags.md#what-the-script-does).
The script is NPU-only by design (`--extra-arg` cannot switch the accelerator,
and an uncompiled model is rejected with exit 2); GPU or non-Tensor runs
(`benchmark_model --use_gpu=true` etc. directly) are outside this skill. Other
options (`--num-runs`, `--performance-mode`, `--signature`,
`--allow-cpu-fallback`, `--no-tile-time`, `--no-power`, ...) are in `--help`.
* **Offline host:** pass both `--benchmark-bin` and `--dispatch-lib`; a
`--dry-run` then shows `user-provided: <path>` for both binaries without
touching the phone or the network - the proof the user wants first.
* **Binary versions:** keep `benchmark_model` and the dispatch library from
the **same** bucket release (the default does; `--benchmark-url
.../binaries/<release>/android_arm64/benchmark_model` pins another one and
the dispatch URL follows). If a provenance md5 differs from
`verified.binaries` in `versions.json`, rerun with `--refresh-binary`
([details](references/benchmark-flags.md#choosing-binary-versions)).
## Step 4 - Report
Nothing in the report is typed by hand. `benchmark_on_device.py` prints a
Markdown header + table (also saved as `report.md` and as the `markdown` field
of `results.json`) in which every value is read from the device or the run.
Paste that block verbatim and add only the context the script cannot know:
```markdown
**Summary:** <NPU "Inference avg" from the table> ms on the TPU vs <CPU "Inference avg"> ms on the CPU (<the N.NNx value from the script's "NPU speed-up vs CPU" line>); peak memory <NPU> vs <CPU> MB; <strict NPU | CPU fallback allowed>. TPU tile time <"TPU tile time / inference" row> ms per inference. TPU energy <"TPU energy / inference" row> mJ per inference.
<header and table exactly as printed by benchmark_on_device.py, including any "Unexpected log lines" section>
**Notes:** <what the Log check line reports: "none" when both logs show 0 unexpected lines and no profiler retry; otherwise each unexpected line with its meaning from references/benchmark-flags.md or troubleshooting.md, plus anything the user should validate>
```
When nothing ran (check exit 2, benchmark exit 2/3/4/5, no device), report
the same way - from output, not from memory:
```markdown
**Not run:** <the script's ERROR line verbatim>
- Device: <the "Device: ..." line printed by benchmark_on_device.py, or the `adb devices -l` line>
- Model: <the "Status: ..." line from check_compiled.py>
- Nothing was pushed to or removed from the phone.
**Options:** <the next actions from step 1 / troubleshooting, most specific first>
```
* NEVER type, round, or "tidy up" numbers, and NEVER reuse values from an
earlier run or from any example in this skill - copy the script output.
Prose numbers (the Summary line) must be character-for-character the
table's values. Never edit `report.md` (script output); if the user wants
the answer saved, write `summary.md` next to it.
* Before writing the Summary and Notes, read
[Writing the report](references/benchmark-flags.md#writing-the-report)
(no CPU baseline, combined compile + benchmark jobs, run counts, CPU
fallback, mixed LiteRT releases, speed-up below 1x, TPU tile time/energy).
## Step 5 - Package for an app (Gradle)
Two cases (Step 0, "New integration or update"); what the package contains and
how the script checks it: [references/app-integration.md](references/app-integration.md).
* **5a - New integration:** an AI pack written by LiteRT's own exporter from
the files as they are (byte-identical, nothing recompiled), the Google
Tensor NPU runtime as an install-time feature module (from Google Maven),
the original model for the app's CPU path, a Kotlin loader, and an
`INTEGRATION.md` with every remaining step for the user's project.
* **5b - Update** (the app already ships Google Tensor builds):
`--update-project` only reads the project and prepares the files to
replace, under the app's own paths and names, plus an `UPDATE.md`.
```bash
# 5a -> <fallback dir>/app_package/<pack name>/INTEGRATION.md and the modules
<venv>/bin/python SKILL_DIR/scripts/package_ai_pack.py \
--compiled /abs/path/compiled/model_Google_Tensor_G5.tflite \
[--compiled /abs/path/compiled/model_Google_Tensor_G6.tflite] \
--fallback /abs/path/model.tflite \
[--delivery install-time|fast-follow|on-demand] [--pack-name NAME] \
[--model-name NAME] [--app-module app] [--kotlin-package com.example.litert] \
[--quick-test] [--output-dir /abs/path/app_package/NAME]
# 5b -> <fallback dir>/app_update/<pack>/UPDATE.md, update.json, files/<paths>
<venv>/bin/python SKILL_DIR/scripts/package_ai_pack.py \
--update-project /abs/path/to/app-project \
--compiled /abs/path/compiled/model_Google_Tensor_G5.tflite \
[--compiled /abs/path/compiled/model_Google_Tensor_G6.tflite] \
--fallback /abs/path/model.tflite \
[--pack-name NAME] [--model-name NAME] [--cpu-asset PATH|none]
```
1. Run `check_compiled.py` on every file first (step 1), and package builds
that passed the strict benchmark (step 3).
2. Run with `--dry-run` first (any `python3`), then for real with a Python
that has `ai-edge-litert`. The script refuses mismatched inputs and never
replaces a directory it did not write.
3. For 5b, show the user the verdict and the file list: `drop-in` (only
model files change), `structural` (`UPDATE.md` section 2 lists the other
changes; list them and ask how to proceed before anything else) or
`up-to-date`. A `Runtime` check of `device` means the new builds must pass
the strict benchmark with the app's own runtime library first (`UPDATE.md`
section 4).
4. Paste the script's `**Packaged:** ...` or `**Update plan:** ...` block
verbatim, add one line (the delivery mode or the verdict in plain words,
and "next: `<output-dir>/INTEGRATION.md`" or `UPDATE.md`), then ask: "The
integration plan is ready (`INTEGRATION.md`). Do you want me to apply it
to your project?" (or "The update plan is ready (`UPDATE.md`). ..."). If
yes, go to step 6. Publishing to Google Play stays with the user.
Exit codes: 0 ok, 2 bad input (missing file, duplicate SoC, invalid name,
output exists, a build that differs from its sidecar, or a project
`--update-project` cannot update as is), 3 wrong model kind (uncompiled
`--compiled`, compiled `--fallback`), 5 LiteRT not importable or its exporter
API changed (the message has the fix), 7 post-export verification failed
(nothing is left at `--output-dir`).
## Step 6 - Apply the plan to the user's project (when they say yes)
You apply the plan; the user approves it once. Before changing anything,
show the **whole plan** and get **one approval**. Then ask **separately** for
each risky item (the check marks them): upgrading the Android Gradle plugin
or Kotlin, adding Kotlin, raising `minSdk`, limiting the app to arm64-v8a
(devices without it can no longer install the app), changing the app's
LiteRT version, replacing project files that differ from the package,
removing a SoC. A declined item is skipped; say what will not work without
it.
* **6a - New integration:** the plan is the `fail` items of a read-only check
(any `python3`, no LiteRT), each with its fix:
```bash
python3 SKILL_DIR/scripts/package_ai_pack.py --check-project /abs/path/to/app-project \
--package <output-dir of step 5a> [--app-module app] [--json]
```
* **6b - Update:** the plan is `UPDATE.md` (the file table and section 2).
Follow the procedure in
[references/app-integration.md](references/app-integration.md#applying-the-plan-skillmd-step-6)
(backups, edits merged in the project's own style, re-check, one build). Never
delete or reformat unrelated code, and never touch signing configs.
## Step 7 - Install and check on a Pixel (when the user agrees)
Builds the user's app, installs it on the attached Pixel the way Google Play
would (bundletool local testing, for the phone's device group), and reads
the loader's `LITERT_TENSOR_RESULT` line:
```bash
python3 SKILL_DIR/scripts/install_and_verify.py --project /abs/path/to/app-project \
[--app-module app] [--variant debug|release|<flavor>Debug] [--serial <id>] \
[--uninstall-first] [--dry-run]
```
Run `--dry-run` first: it shows the phone, its device group and whether the
NPU path is expected. Exit 7 means the app is already installed and local
testing cannot update it: ask the user (uninstalling deletes the app's data on
the phone), then rerun with `--uninstall-first`. The app must call
`TensorModelLoader.load()`; if it loads the model on a particular screen, tell
the user to open it while the script waits. Report the script's block
verbatim: `"path":"npu"` is the pass; for `"path":"cpu"` on a phone the app
has a build for, the `npu_error` says why. Requirements and exit codes:
[references/app-integration.md](references/app-integration.md#checking-on-a-pixel-skillmd-step-7).
## Rules
* ALWAYS run `check_compiled.py` before compiling or benchmarking, on every
model file involved - the compiler cannot recompile a compiled model, and
the TPU cannot run an uncompiled one.
* ALWAYS verify the device SoC matches the model's stamp (the benchmark
script does) - a `Tensor_G5` model on a `Tensor_G6` phone fails with an
opaque dispatch error, wasting a debugging round.
* ALWAYS use the original uncompiled model for `--cpu-baseline` - compiled
models contain `DISPATCH_OP` nodes that only the NPU can execute.
* ALWAYS clean up the per-run device directory (automatic; after an
interrupted run list the base first, then remove only its `run-*` entries:
`adb shell ls -la <base>` and `adb shell rm -rf <base>/run-*`, where
`<base>` is `/data/local/tmp/litert_benchmark` or the `--device-dir` that
was used). NEVER `rm -rf` the base directory itself - users keep their own
binaries and models there.
* NEVER combine `--use_cpu=true` with `--require_full_delegation=true` -
`benchmark_model` aborts on that combination.
* NEVER install packages into the system interpreter or without telling the
user; use a virtualenv so pinned LiteRT versions do not break other work.
* NEVER type LiteRT version numbers into install commands or download URLs
yourself - take them from `compile_model.py --print-install` and the
scripts' default URLs, which all read `versions.json`, so every job uses the
pair that was verified together. Use another release only when the user
asks for one (`--benchmark-url`, or the pip pair at that version), and say
so in the report. Changing the pin is a maintainer task
([references/contributing.md](references/contributing.md)).
* NEVER treat macOS, Windows, or ARM hosts as a compile blocker or give manual
browser Colab notebook steps - run `compile_model.py --colab` directly.
* NEVER leave adb, benchmark, or Colab VM sessions running in the background -
every command here is bounded by a timeout and returns before the next step
(`compile_model.py --colab` stops any Colab VM it creates unless
`--keep-colab-session` is passed).
* NEVER guess compile flags or overwrite an existing output without asking
(`compile_model.py` exits 2; use `--output-name` or ask before
`--overwrite`).
* ALWAYS package for an app with `package_ai_pack.py` (it calls LiteRT's
exporter and verifies the result), and with `--update-project` (step 5b)
when the app already ships Google Tensor builds; NEVER create or edit AI
pack folders, the device-targeting XML or the runtime modules by hand, and
NEVER copy a new package's `ai_packs/` over an existing pack - the app's
group names and the place of its CPU copy can differ.
* ALWAYS ask before changing the user's project, show the whole plan, and
get one approval; ask separately for each risky item (step 6) and before
`install_and_verify.py --uninstall-first`. NEVER change signing configs.
* NEVER put a compiled build where the app runs on the CPU (base assets,
`--fallback`): only the original uncompiled model.
* NEVER publish to Google Play, sign, or upload anything for the user; the
skill stops at the package and the local-testing steps.
## Troubleshooting
Every script error names its fix; look up the error line or exit code in
[references/troubleshooting.md](references/troubleshooting.md).
## Public references
[LiteRT NPU guide](https://developers.google.com/edge/litert/next/npu),
[Google Tensor with LiteRT](https://developers.google.com/edge/litert/next/tensor-sdk),
[compilation flags](https://developers.google.com/edge/tensor-sdk/compilation-flags),
[Tensor SDK FAQ](https://developers.google.com/edge/tensor-sdk/tensor-faqs),
[release notes / compatibility](https://developers.google.com/edge/tensor-sdk/release-notes),
[benchmark_model](https://developers.google.com/edge/litert/next/benchmark),
[codelab](https://codelabs.developers.google.com/codelabs/google-tensor-ml-sdk),
[Play for On-device AI](https://developer.android.com/google/play/on-device-ai).
## Contributions
To contribute or modify this skill or its references, follow the
[contribution guidelines](references/contributing.md) before making changes.
INTEGRATION.md 7.5 KB
# Add "{{MODEL_NAME}}" to your Android app (Google Tensor TPU)
Generated by litert-google-tensor `package_ai_pack.py` on {{GENERATED_AT}}.
Every value below comes from this package; `pack.json` records where each file
came from. Your coding agent can apply these steps to your project for you:
it shows the whole plan first, asks separately before risky changes, and can
then install the app on your Pixel to check it.
| | |
|---|---|
| AI pack | `{{PACK_NAME}}`, `{{DELIVERY}}` delivery |
| Google Tensor builds | {{GROUP_LIST}} |
| All other devices | the original model on the CPU, from your app's base assets |
| LiteRT (Maven) | `com.google.ai.edge.litert:litert:{{LITERT_MAVEN_RELEASE}}` and `com.google.ai.edge.litert:litert-npu-runtime-google-tensor:{{LITERT_MAVEN_RELEASE}}` |
Google Play delivers each phone only the files of its own device group, so a
Pixel with a packaged SoC downloads only its Tensor build, and other phones
download none.
Your app does not need any LiteRT or NPU code yet. These steps add everything:
the LiteRT runtime, the Google Tensor NPU runtime
(`libLiteRtDispatch_GoogleTensor.so`, inside the Maven artifact above), the
models, and the code that loads them. The TPU driver that the runtime talks to
ships on the Pixel itself.
## What is in this folder
```text
{{TREE}}
```
## Requirements
- Android Gradle plugin 8.10 or newer (AI packs need 8.8, device targeting
8.10).
- Kotlin {{KOTLIN_MIN}} or newer (the Kotlin Gradle plugin): older Kotlin
compilers cannot read LiteRT {{LITERT_MAVEN_RELEASE}}'s Kotlin API.
- `minSdk` 31 or higher.
- arm64-v8a only (`abiFilters`, step 6): bundletool requires the same ABIs in
every module that has native libraries, and the Google Tensor runtime has
only arm64-v8a. Devices that do not support arm64-v8a can then no longer
install the app.
- The Google Tensor NPU itself is used only on Android 16 (API 36) or newer
with NPU support; other devices and builds get the CPU model.
- Nothing else to download: the NPU runtime comes from Google Maven.
## Steps
1. **Copy the modules** into your project root, keeping the paths:
`ai_packs/{{PACK_NAME}}/` and `litert_npu_runtime_libraries/` (two modules:
`google_tensor_runtime` and `runtime_strings`). If your project already
has LiteRT's `litert_npu_runtime_libraries/runtime_strings`, keep yours.
2. **Device targeting:** copy `ai_packs/device_targeting_configuration.xml` to
`{{APP_MODULE_DIR}}/device_targeting_configuration.xml`. If the app already
has one, add these `<config:device-group>` elements to it, unchanged: the
same names are used by the AI pack folders and by the
`google_tensor_runtime` module.
3. **CPU model:** copy `cpu_gpu/{{MODEL_NAME}}_cpu_gpu.tflite` to
`{{APP_MODULE_DIR}}/src/main/assets/litert/`.
4. **Loader:** copy `kotlin/TensorModelLoader.kt` into your sources and set
its `package` line (now `{{KOTLIN_PACKAGE}}`) to where you put it.
5. **`settings.gradle.kts`:**
```kotlin
include(":ai_packs:{{PACK_NAME}}")
include(":litert_npu_runtime_libraries:runtime_strings")
include(":litert_npu_runtime_libraries:google_tensor_runtime")
```
6. **`{{APP_MODULE_DIR}}/build.gradle.kts`:**
```kotlin
android {
defaultConfig {
minSdk = 31 // or higher
ndk { abiFilters.add("arm64-v8a") }
}
// LiteRT finds the NPU runtime by listing the app's native library
// directory, so native libraries must be extracted at install time.
packaging { jniLibs { useLegacyPackaging = true } }
assetPacks.add(":ai_packs:{{PACK_NAME}}")
dynamicFeatures.add(":litert_npu_runtime_libraries:google_tensor_runtime")
bundle {
deviceTargetingConfig = file("device_targeting_configuration.xml")
deviceGroup {
enableSplit = true
defaultGroup = "other"
}
}
}
dependencies {
implementation("com.google.ai.edge.litert:litert:{{LITERT_MAVEN_RELEASE}}")
implementation(project(":litert_npu_runtime_libraries:runtime_strings"))
}
```
Groovy DSL: the same blocks with `assetPacks = [":ai_packs:{{PACK_NAME}}"]`,
`dynamicFeatures = [":litert_npu_runtime_libraries:google_tensor_runtime"]`
and `deviceTargetingConfig = file('device_targeting_configuration.xml')`.
The `google_tensor_runtime` module depends on `project(":{{APP_MODULE}}")`;
change that line if your app module has another name.
7. **`gradle.properties`:** `android.experimental.enableDeviceTargetingConfigApi=true`
8. **Manifest:** {{PERMISSIONS_STEP}}
9. **Use the model:**
```kotlin
// In a coroutine, off the main thread:
val loaded = TensorModelLoader.load(context) // keep it while you need it
val inputs = loaded.model.createInputBuffers()
val outputs = loaded.model.createOutputBuffers()
inputs[0].writeFloat(myInput)
loaded.model.run(inputs, outputs)
val result = outputs[0].readFloat()
```
`model_io.json` lists the model's input and output names, shapes and
types. Close the buffers, then `loaded.close()`, when you are done.
## Test on a Pixel before releasing
```bash
./gradlew :{{APP_MODULE}}:bundleRelease # or bundleDebug
java -jar bundletool-all.jar build-apks --local-testing --overwrite \
--bundle={{APP_MODULE_DIR}}/build/outputs/bundle/release/{{APP_MODULE_LAST}}-release.aab \
--output=/tmp/app.apks
java -jar bundletool-all.jar install-apks --apks=/tmp/app.apks \
--device-groups={{FIRST_GROUP}}
adb shell pm path <your.application.id> # expect a google_tensor_runtime split
adb logcat -s LiteRtTensor # after the app loads the model
```
- `--device-groups` is the phone's group: `adb shell getprop ro.soc.model`
prints `Tensor G5` for `Google_Tensor_G5`, `Tensor G6` for
`Google_Tensor_G6`.
- `./gradlew installDebug` installs only the base APK, without the AI pack
and the `google_tensor_runtime` module, so the loader falls back to the CPU
model. Test with the bundletool commands above: they install what Google
Play would deliver to the phone.
- Use `bundletool-all-<version>.jar` 1.18.0 or newer from
https://github.com/google/bundletool/releases: it includes aapt2. Other
bundletool builds need `--aapt2=<Android SDK>/build-tools/<version>/aapt2`
on `build-apks`.
- The log line reads `LITERT_TENSOR_RESULT {"path":"npu", ...}` when the model
runs on the TPU. `"path":"cpu"` comes with an `npu_error` saying why.
- Local testing cannot update an installed app: uninstall it first.
`fast-follow` packs behave like `on-demand` packs in local testing.
{{QUICK_TEST_SECTION}}
## Release
Upload the AAB to Google Play, internal testing track first. Play delivers the
AI pack variant and the `google_tensor_runtime` module only to the devices in
the groups above.
## If something fails
| Symptom | Fix |
|---|---|
| bundletool: `Module '...' refers to device groups [...] which are not in the list [...]` | The app's `device_targeting_configuration.xml` is missing a group: copy it from this package (step 2). |
| Gradle: `Plugin with id 'com.android.ai-pack' not found` | The Android Gradle plugin is older than 8.8, or not declared in the root build file. |
| Kotlin: `class 'com.google.ai.edge.litert...' was compiled with an incompatible version of Kotlin` | Use Kotlin {{KOTLIN_MIN}} or newer for the app. |
| `"path":"cpu"` with `npu_error` about the device | Expected on other phones and on Android builds without NPU support. |
| `"path":"cpu"` on a packaged Pixel | Check `adb shell pm path` for the `google_tensor_runtime` split, `useLegacyPackaging = true`, and that `litert` and `litert-npu-runtime-google-tensor` have the same version. |
INTEGRATION_quick_test.md 1.9 KB
## Optional: quick test without bundletool
`quick_test/` holds a copy of each Google Tensor build, laid out so that the
debug APK can carry it together with the NPU runtime. Then
`./gradlew installDebug` runs the model on your Pixel's TPU, without
bundletool, the AI pack or the runtime feature module. It is for trying the
model on your own phone only: nothing changes unless you pass
`-PtensorQuickTest`, and even then only the debug build changes, so what you
upload to Google Play is unaffected.
1. Copy `quick_test/` to `{{APP_MODULE_DIR}}/tensor_quick_test/`. It holds a
full copy of each build, so you may want to add it to `.gitignore`.
2. Add at the end of `{{APP_MODULE_DIR}}/build.gradle.kts`:
```kotlin
// Quick test on a Pixel without bundletool (debug builds only):
// ./gradlew :{{APP_MODULE}}:installDebug -PtensorQuickTest={{FIRST_SOC}}
// The debug APK then carries the Google Tensor build and the NPU runtime.
providers.gradleProperty("tensorQuickTest").orNull?.let { soc ->
android.sourceSets.getByName("debug")
.assets.srcDir("tensor_quick_test/$soc/assets")
dependencies.add(
"debugImplementation",
"com.google.ai.edge.litert:litert-npu-runtime-google-tensor:{{LITERT_MAVEN_RELEASE}}",
)
}
```
Groovy DSL: `def soc = providers.gradleProperty('tensorQuickTest').orNull`,
then, inside `if (soc != null) { ... }`,
`android.sourceSets.debug.assets.srcDir("tensor_quick_test/$soc/assets")`
and the same `dependencies.add(...)` call.
3. Run `./gradlew :{{APP_MODULE}}:installDebug -PtensorQuickTest=<SoC>`, with
the phone's SoC written with an underscore: `adb shell getprop ro.soc.model`
prints `Tensor G5` for `Tensor_G5` (this package has builds for
{{QUICK_TEST_SOCS}}). Start the app and check
`adb logcat -s LiteRtTensor` for `"path":"npu"`.
Without `-PtensorQuickTest`, `installDebug` installs the base APK only, and
the model runs on the CPU.
TensorModelLoader.kt 7.1 KB
/*
* Copyright 2026 The Google AI Edge Authors. All Rights Reserved.
*
* 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.
*/
// Generated by litert-google-tensor (scripts/package_ai_pack.py) for the AI
// pack "{{PACK_NAME}}". On the Pixel SoCs that have a Google Tensor build in
// the pack ({{SOC_LIST_TEXT}}) it runs "{{MODEL_NAME}}" on the TPU; everywhere
// else - or if the TPU path fails - it runs the original model on the CPU.
//
// Usage (from a coroutine, off the main thread):
//
// val loaded = TensorModelLoader.load(context) // keep it while you need it
// val inputs = loaded.model.createInputBuffers()
// val outputs = loaded.model.createOutputBuffers()
// inputs[0].writeFloat(myInput) // your pre-processing
// loaded.model.run(inputs, outputs)
// val result = outputs[0].readFloat() // your post-processing
// // When done: close the buffers, then loaded.close().
//
// Every load() logs one line, tag "LiteRtTensor", starting with
// "LITERT_TENSOR_RESULT " and followed by JSON: {"path":"npu"|"cpu", ...}.
// See INTEGRATION.md next to the generated AI pack.
package {{KOTLIN_PACKAGE}}
import android.content.Context
import android.os.Build
import android.os.SystemClock
import android.util.Log
import com.google.ai.edge.litert.Accelerator
import com.google.ai.edge.litert.BuiltinNpuAcceleratorProvider
import com.google.ai.edge.litert.CompiledModel
import com.google.ai.edge.litert.Environment
import com.google.ai.edge.litert.ModelProvider
import com.google.ai.edge.litert.ModelSelector
import com.google.ai.edge.litert.NpuCompatibilityChecker
import com.google.ai.edge.litert.deployment.AiPackModelProvider
import java.io.IOException
import kotlin.coroutines.cancellation.CancellationException
import org.json.JSONObject
object TensorModelLoader {
/** Name of the AI pack (its directory and `aiPack.packName`). */
const val AI_PACK_NAME = "{{PACK_NAME}}"
/** The model inside the AI pack, without the `#group_...` suffix. */
const val PACK_MODEL_PATH = "model/{{MODEL_NAME}}.tflite"
/** The original (uncompiled) model in the app's base assets: the CPU path. */
const val CPU_MODEL_ASSET = "litert/{{MODEL_NAME}}_cpu_gpu.tflite"
/** `aiPack.dynamicDelivery.deliveryType` of the AI pack. */
const val DELIVERY = "{{DELIVERY}}"
/** `Build.SOC_MODEL` values that have a Google Tensor build in the pack. */
val PACKAGED_SOC_MODELS: Set<String> = setOf({{SOC_MODELS_KOTLIN}})
const val LOG_TAG = "LiteRtTensor"
const val RESULT_PREFIX = "LITERT_TENSOR_RESULT "
/** Which model [load] returned. */
enum class Path {
/** The Google Tensor build from the AI pack, on the TPU. */
NPU,
/** The original model from the base assets, on the CPU. */
CPU,
}
/** A loaded model. Close it (after its tensor buffers) when done. */
class Loaded
internal constructor(
val model: CompiledModel,
val path: Path,
val loadMs: Long,
/** Why the TPU path was not used, or null. */
val npuError: String?,
private val environment: Environment?,
) : AutoCloseable {
override fun close() {
model.close()
environment?.close()
}
}
/**
* True on devices that should run the Google Tensor build: LiteRT's own
* Google Tensor check (Android version and build) plus an SoC that has a
* build in the pack.
*/
fun isPackagedTensorDevice(): Boolean =
NpuCompatibilityChecker.GoogleTensor.isDeviceSupported() &&
Build.SOC_MODEL.trim() in PACKAGED_SOC_MODELS
/** Loads the Google Tensor build on the TPU if possible, else the CPU model. */
suspend fun load(context: Context): Loaded {
val start = SystemClock.elapsedRealtime()
var npuError: String? = null
if (isPackagedTensorDevice()) {
var environment: Environment? = null
try {
environment =
Environment.create(
BuiltinNpuAcceleratorProvider(context, NpuCompatibilityChecker.GoogleTensor)
)
val model = loadTensorBuild(context, environment)
val elapsed = SystemClock.elapsedRealtime() - start
return report(Loaded(model, Path.NPU, elapsed, null, environment))
} catch (e: CancellationException) {
environment?.close()
throw e
} catch (e: Exception) {
environment?.close()
npuError = "${e.javaClass.simpleName}: ${e.message}"
Log.w(LOG_TAG, "Google Tensor TPU path failed; using the CPU model.", e)
}
} else {
npuError = "not a packaged Google Tensor device (SoC: ${Build.SOC_MODEL})"
}
val model =
CompiledModel.create(context.assets, CPU_MODEL_ASSET, CompiledModel.Options(Accelerator.CPU))
val elapsed = SystemClock.elapsedRealtime() - start
return report(Loaded(model, Path.CPU, elapsed, npuError, null))
}
private suspend fun loadTensorBuild(context: Context, environment: Environment): CompiledModel {
val provider: ModelProvider =
if (DELIVERY == "install-time" || isAppAsset(context, PACK_MODEL_PATH)) {
// An install-time AI pack, or a debug build that carries the model
// itself (the optional quick test in INTEGRATION.md).
ModelProvider.staticModel(ModelProvider.Type.ASSET, PACK_MODEL_PATH, Accelerator.NPU)
} else {
// fast-follow / on-demand: downloads the pack if it is not on the device yet.
AiPackModelProvider(context, AI_PACK_NAME, PACK_MODEL_PATH, Accelerator.NPU)
}
// Throws IllegalStateException if the NPU is unavailable or the download fails.
val selected = ModelSelector(provider).selectModel(environment)
val options = CompiledModel.Options(Accelerator.NPU)
return if (selected.getType() == ModelProvider.Type.ASSET) {
// Install-time AI pack assets: read them through a fresh package context.
val assets = context.createPackageContext(context.packageName, 0).assets
CompiledModel.create(assets, selected.getPath(), options, environment)
} else {
CompiledModel.create(selected.getPath(), options, environment)
}
}
/** True if the app's own APK assets contain [path]. */
private fun isAppAsset(context: Context, path: String): Boolean =
try {
context.assets.open(path).close()
true
} catch (e: IOException) {
false
}
private fun report(loaded: Loaded): Loaded {
val result =
JSONObject()
.put("path", loaded.path.name.lowercase())
.put("soc", Build.SOC_MODEL)
.put("sdk", Build.VERSION.SDK_INT)
.put("build_id", Build.ID)
.put("pack", AI_PACK_NAME)
.put("delivery", DELIVERY)
.put("load_ms", loaded.loadMs)
.put("npu_error", loaded.npuError ?: JSONObject.NULL)
Log.i(LOG_TAG, RESULT_PREFIX + result)
return loaded
}
}
UPDATE.md 1.9 KB
# Update "{{MODEL_PATH}}" in your app (Google Tensor TPU)
Generated by litert-google-tensor `package_ai_pack.py --update-project` on
{{GENERATED_AT}} for `{{PROJECT_DIR}}`. The project was only read, not
changed: the new files are in `files/`, at the same paths as in the
project, and `update.json` records where each one came from. Your coding
agent can apply this plan for you: it shows it first, asks separately before
risky changes, and can then install the app on your Pixel to check it.
**{{VERDICT}}.**
| | |
|---|---|
{{SUMMARY_ROWS}}
## 1. Files to copy into the project
{{FILE_TABLE}}
Copy each file from `files/<path>` to `<project>/<path>`, one at a time,
keeping every name: the app opens `{{MODEL_PATH}}` (Google Play strips the
`#group_...` part of the folder name). Keep the old files (commit first, or
copy them aside) so you can go back. Rows marked `unchanged` need nothing.
## 2. Changes outside the model files
{{EDITS}}
## 3. Checks
| Check | Result | Details |
|---|---|---|
{{CHECK_ROWS}}
`pass`: nothing to do. `edit`: a change in section 2. `device`: run the
check in section 4. `info` and `unknown`: read the details.
## 4. Run the new builds with the app's runtime
{{DEVICE_CHECK}}
## 5. Rebuild, test, release
1. {{VERSION_CODE_STEP}}
2. Build the app bundle and install it on a Pixel the way Google Play would:
```bash
{{TEST_COMMANDS}}
```
Local testing cannot update an installed app, hence the uninstall.
`./gradlew installDebug` installs no AI packs, so it would test only the
CPU model. `--device-groups` is the phone's group:
`adb shell getprop ro.soc.model` prints its SoC (section 3, "Names").
3. Upload the app bundle to Google Play, internal testing track first.
{{DELIVERY_UPDATE}} Only phones in the Google Tensor groups download a
Tensor build.
After copying the files, run the same `package_ai_pack.py --update-project`
command with `--dry-run`: every file then shows as `unchanged`.
build.gradle.kts 1.2 KB
/*
* Copyright 2026 The Google AI Edge Authors. All Rights Reserved.
*
* 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.
*/
// Generated by litert-google-tensor (scripts/package_ai_pack.py).
// Google Play AI pack with the Google Tensor builds of "{{MODEL_NAME}}":
// src/main/assets/model#group_<device group>/{{MODEL_NAME}}.tflite. Google Play
// strips the "#group_..." suffix, so the app always opens
// "model/{{MODEL_NAME}}.tflite". Do not edit the model files by hand; re-run
// package_ai_pack.py instead. See INTEGRATION.md next to this pack.
plugins { id("com.android.ai-pack") }
aiPack {
packName = "{{PACK_NAME}}"
dynamicDelivery { deliveryType = "{{DELIVERY}}" }
}
build.gradle.kts 1.5 KB
/*
* Copyright 2026 The Google AI Edge Authors. All Rights Reserved.
*
* 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.
*/
// Generated by litert-google-tensor (scripts/package_ai_pack.py).
// Install-time dynamic feature module that delivers the Google Tensor NPU
// runtime (libLiteRtDispatch_GoogleTensor.so, from the Maven artifact below)
// only to the device groups listed in src/main/AndroidManifest.xml - the
// same groups as the AI pack. Same layout as the google_tensor_runtime module
// of LiteRT's NPU guide: https://developers.google.com/edge/litert/next/npu
plugins { id("com.android.dynamic-feature") }
android {
namespace = "com.google.ai.edge.litert.google_tensor_runtime"
compileSdk = 35
defaultConfig { minSdk = 31 }
}
dependencies {
implementation(project(":{{APP_MODULE}}"))
// Must be the same release as com.google.ai.edge.litert:litert in the app.
implementation("com.google.ai.edge.litert:litert-npu-runtime-google-tensor:{{LITERT_MAVEN_RELEASE}}")
}
AndroidManifest.xml 1.5 KB
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2026 The Google AI Edge Authors. All Rights Reserved.
~
~ 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.
-->
<!-- Generated by litert-google-tensor (scripts/package_ai_pack.py).
Install-time feature module, delivered only to the device groups that
have a Google Tensor build in the AI pack. Every group listed here must
also be defined in the app's device_targeting_configuration.xml. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution">
<dist:module
dist:instant="false"
dist:title="@string/title_google_tensor_runtime">
<dist:delivery>
<dist:install-time>
<dist:conditions>
<dist:device-groups>
{{DEVICE_GROUP_ELEMENTS}}
</dist:device-groups>
</dist:conditions>
</dist:install-time>
</dist:delivery>
<dist:fusing dist:include="true" />
</dist:module>
</manifest>
build.gradle.kts 1.1 KB
/*
* Copyright 2026 The Google AI Edge Authors. All Rights Reserved.
*
* 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.
*/
// Generated by litert-google-tensor (scripts/package_ai_pack.py).
// Holds the title string of the google_tensor_runtime feature module: a
// dynamic feature's dist:title must resolve from a module the app depends on.
// Same layout as the runtime_strings module of LiteRT's NPU guide.
plugins { id("com.android.library") }
android {
namespace = "com.google.ai.edge.litert.runtime_strings"
compileSdk = 35
defaultConfig { minSdk = 31 }
}
strings.xml 0.8 KB
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2026 The Google AI Edge Authors. All Rights Reserved.
~
~ 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.
-->
<!-- Generated by litert-google-tensor (scripts/package_ai_pack.py). -->
<resources>
<string name="title_google_tensor_runtime">Google Tensor NPU Runtime</string>
</resources>
versions.json 5.2 KB
{
"_comment": [
"Single source of the LiteRT versions this skill installs and downloads.",
"compile_model.py reads pip_release and python (--print-install, install hints, installed-version check).",
"benchmark_on_device.py reads binaries_release (default download URL) and pip_release (Versions line).",
"package_ai_pack.py reads maven_release: the Google Maven version of com.google.ai.edge.litert:litert and com.google.ai.edge.litert:litert-npu-runtime-google-tensor that it writes into the generated Gradle files and INTEGRATION.md. Both artifacts must exist at that version (on 2026-10-27 Google Maven listed 2.3.0 and 2.3.2 for both, and no 2.3.1).",
"package_ai_pack.py also reads kotlin_min: the oldest Kotlin (Gradle plugin) version that can read the Kotlin metadata of com.google.ai.edge.litert:litert-api at maven_release; INTEGRATION.md tells users to use it or newer. litert-api 2.3.0 carries Kotlin metadata 2.4.0, which Kotlin 2.3 reads and Kotlin 2.1 rejects (checked 2026-10-14 by compiling assets/templates/TensorModelLoader.kt with Kotlin 2.1.0 and 2.3.21); litert-api 2.3.2 carries the same metadata 2.4.0 (javap, and the verified.app builds with Kotlin 2.3.21, 2026-10-27).",
"scripts/install_and_verify.py reads bundletool_release: without --bundletool it downloads bundletool-all-<bundletool_release>.jar from https://github.com/google/bundletool/releases (cached in ~/.cache/litert-google-tensor/). Local testing of AI packs needs 1.18.0 or newer.",
"SKILL.md and references/ never repeat these values as instructions; observations there name the version they were seen with.",
"The two releases differ because the pip packages and the binaries bucket are separate sources (references/contributing.md, \"Why two release fields\"). pip_release stays at 2.1.6, the stable ai-edge-litert release in the Tensor SDK compatibility matrix and the one verified with this skill; the 2.3.1 binaries run models compiled with it (see verified).",
"binaries/2.3.1/ was uploaded twice: on 2026-10-20 with a libLiteRtDispatch_GoogleTensor.so byte-identical to 2.3.0's (its TPU tile-time and power hooks count every inference twice), and again on 2026-10-23 17:54 UTC with a rebuilt library that counts once per dispatch invoke. The pin is the second upload (md5s in verified.binaries); a copy fetched before then stays cached under the same name (~/.cache/litert-google-tensor/2.3.1_android_arm64_*) until --refresh-binary.",
"maven_release and binaries_release differ too: Google Maven skipped 2.3.1, and the bucket has no 2.3.2 (both checked 2026-10-27). The libLiteRtDispatch_GoogleTensor.so in the litert-npu-runtime-google-tensor 2.3.2 AAR is a different build than the bucket's 2.3.1 library (579,024 vs 629,984 bytes) with the same hook fix: TPU tile time and energy counted once per dispatch invoke (verified.app). The 2.3.0 AAR's library has the old hooks.",
"Change this file only by following references/contributing.md."
],
"pip_release": "2.1.6",
"binaries_release": "2.3.1",
"maven_release": "2.3.2",
"bundletool_release": "1.18.3",
"kotlin_min": "2.3",
"python": "3.10-3.13",
"verified": {
"date": "2026-10-26",
"evidence": "the efficientnet_b7 example in references/benchmark-flags.md (\"Example with TPU tile time and energy\"): compiled with ai-edge-litert 2.1.6 (930/930 ops), then strict NPU (1 of 1 nodes delegated) + CPU baseline on the 2.3.1 binaries, with TPU tile time and TPU energy (both hooks counted 1 call per run)",
"device": "Pixel 10 (Tensor G5), Android 17 build CP2A.260705.006.A1",
"host": "Linux x86_64, Python 3.13",
"binaries": "bucket release 2.3.1 as re-uploaded 2026-10-23 17:54 UTC, fetched 2026-10-26: benchmark_model md5 bx6O455Ns4gjZWozKljNfQ==, libLiteRtDispatch_GoogleTensor.so md5 tp26wryZhjaU3IYIz2w7/g==",
"app": "2026-10-27, Pixel 10 (Tensor G5), Android 17 build CP2A.260705.006.A1, Maven litert + litert-npu-runtime-google-tensor 2.3.2, efficientnet_b7 compiled with ai-edge-litert 2.1.6 (930/930 ops), bundletool 1.18.3 (AGP 8.13.1, Gradle 8.13, Kotlin 2.3.21, JDK 21): end-to-end run (package, Gradle build, bundletool install, launch) PASS for install-time and on-demand, and the optional quick test (on-demand: installDebug -PtensorQuickTest=Tensor_G5, no bundletool) PASS, all on the NPU, with outputs for fixed inputs identical to 2.3.0's (same SHA-256); SKILL.md steps 6-7 on the plain test app (no LiteRT, Kotlin 2.0.21, minSdk 26): package_ai_pack.py --check-project plan applied (Kotlin 2.3.21, minSdk 31, arm64-v8a only), re-check 19/19 passed, install_and_verify.py PASS (path npu, install-time; bundletool jars from Google Maven via --bundletool <folder>), and the app's own inference ran on the NPU; the dispatch library of the 2.3.2 Maven AAR passed the strict benchmark with TPU tile time and TPU energy, both hooks counting 1 call per run (26.45 ms average, tile time 17.891 ms, energy 21.438 mJ; the bucket's 2.3.1 library in the next run: 26.86 / 18.168 / 21.643). Not rerun with 2.3.2 (PASS with 2.3.0 on 2026-10-14 and 2026-10-15): the update flow (package_ai_pack.py --update-project to a --truncation-type half build, then rebuilt, installed and run), and install_and_verify.py stopping with exit 7 on a rerun and reinstalling with --uninstall-first"
}
}
app-integration.md 32.6 KB
# Packaging a compiled model for an Android app
Reference for `scripts/package_ai_pack.py` (SKILL.md steps 5 and 6) and
`scripts/install_and_verify.py` (step 7). The user-facing steps live in the
`INTEGRATION.md` the script writes next to each package (template:
`assets/templates/INTEGRATION.md`); this file explains what the package
contains, why, and how to check it. Everything here uses public tools only:
Gradle, the Android Gradle plugin, Google Play, bundletool and LiteRT's
published Maven and PyPI packages.
## Contents
- [How it fits together](#how-it-fits-together): Lines 30-77
- [Why `model#group_other` holds a placeholder](#why-modelgroup_other-holds-a-placeholder): Lines 57-66
- [Why the script calls LiteRT's exporter](#why-the-script-calls-literts-exporter): Lines 68-77
- [Delivery modes (asked in Step 0)](#delivery-modes-asked-in-step-0): Lines 79-96
- [Runtime facts behind the generated files](#runtime-facts-behind-the-generated-files): Lines 98-112
- [Checking a package](#checking-a-package): Lines 114-145
- [Quick test without bundletool (`--quick-test`)](#quick-test-without-bundletool---quick-test): Lines 147-165
- [Updating builds an app already ships](#updating-builds-an-app-already-ships): Lines 167-224
- [What the script reads](#what-the-script-reads): Lines 174-186
- [Verdicts](#verdicts): Lines 188-213
- [Delivering an update](#delivering-an-update): Lines 215-224
- [Applying the plan (SKILL.md step 6)](#applying-the-plan-skillmd-step-6): Lines 226-314
- [New integration (6a)](#new-integration-6a): Lines 235-301
- [Update (6b)](#update-6b): Lines 303-314
- [Checking on a Pixel (SKILL.md step 7)](#checking-on-a-pixel-skillmd-step-7): Lines 316-371
- [Public references](#public-references): Lines 373-386
## How it fits together
The package works for an app with no LiteRT or NPU support yet: together with
the `INTEGRATION.md` steps it adds the LiteRT runtime
(`com.google.ai.edge.litert:litert`), the Google Tensor NPU runtime
(`libLiteRtDispatch_GoogleTensor.so`, in the runtime feature module), the
models and the loading code. Nothing is copied from the phone or built from
source: the TPU driver the runtime uses ships on the Pixel itself.
| Piece | What it is | Where it comes from |
|---|---|---|
| AI pack `ai_packs/<pack>/` | Google Play AI pack (`com.android.ai-pack` Gradle plugin) with one folder per device group: `model#group_Google_Tensor_G5/<model>.tflite`, `model#group_Google_Tensor_G6/...`, and `model#group_other/placeholder.txt` | Written by LiteRT's exporter, `ai_edge_litert.aot.ai_pack.export_lib`, from the compiled files as they are (byte-identical); the script adds `build.gradle.kts` and replaces the `other` copy with a placeholder |
| `device_targeting_configuration.xml` | Defines the device groups: `Google_Tensor_G5` = SoC manufacturer `Google`, model `Tensor G5` (same for G6) | Written by the exporter |
| `litert_npu_runtime_libraries/google_tensor_runtime/` | Install-time dynamic feature module delivering `libLiteRtDispatch_GoogleTensor.so`, only to the pack's device groups | Generated from `assets/templates/`; the library itself is the Maven artifact `com.google.ai.edge.litert:litert-npu-runtime-google-tensor` |
| `litert_npu_runtime_libraries/runtime_strings/` | Library module holding the feature module's title string | Generated from `assets/templates/` |
| `cpu_gpu/<model>_cpu_gpu.tflite` | The original model, for the app's base assets (`litert/`): the CPU path | Copy of `--fallback` |
| `kotlin/TensorModelLoader.kt` | Loads the Tensor build on packaged Pixels, else the CPU model; logs one result line | Generated from `assets/templates/` |
| `quick_test/<SoC>/assets/model/<model>.tflite` (only with `--quick-test`) | A copy of each Tensor build for the optional quick test (below) | Copy of the exporter's output, byte-identical |
| `model_io.json` | Input/output names, shapes and types of the original model | Read with `ai_edge_litert.interpreter.Interpreter` |
| `pack.json` | Provenance: every source path and SHA-256, sidecar flags, versions, the checks that passed | Written by the script |
Google Play splits the bundle by device group: a Pixel 10 (Tensor G5)
installs the `Google_Tensor_G5` variant of the pack and the runtime module;
other phones get the `other` variant (the placeholder) and no runtime module,
and run the CPU model from the base assets. The app always opens
`model/<model>.tflite`; Play strips the `#group_...` suffix.
### Why `model#group_other` holds a placeholder
The app needs the original model in its base assets anyway: it is the
fallback when the TPU path fails on a Pixel (for example on an Android build
without NPU support). If the pack's `other` folder also held the original,
phones outside the Tensor groups would download it twice with `install-time`
delivery. The placeholder keeps the folder (bundletool requires every
device-group folder set to be consistent) without the second copy. The
exporter uses the same technique for its MediaTek pack. This is the only
change the script makes to the exporter's output, and its checks confirm it.
### Why the script calls LiteRT's exporter
The pack layout and the device-targeting XML come from
`export_lib.export()`, so they follow LiteRT when the pinned version changes.
The script builds the exporter's input from files on disk (one
`GoogleTensorBackend` per stamped SoC plus a `FallbackBackend` for the
original); neither touches the compiler, so packaging needs `ai-edge-litert`
but not the Google Tensor SDK Beta, and nothing is recompiled. If the
exporter's API changes, the script exits 5 instead of guessing a layout
(`references/contributing.md` covers adopting such a release).
## Delivery modes (asked in Step 0)
One line in the pack's `build.gradle.kts`
(`dynamicDelivery { deliveryType = "..." }`) decides when Google Play puts
the model on the phone. In every mode a phone receives only its own group's
files.
| Mode | When the model arrives | What the app needs | Pick it when |
|---|---|---|---|
| `install-time` (default) | With the app, ready at first launch | Nothing extra; the loader reads it as an asset | Most apps; the simplest and most robust |
| `fast-follow` | Downloaded automatically right after install | Play AI Delivery library (pulled in by LiteRT) and the `FOREGROUND_SERVICE` / `FOREGROUND_SERVICE_DATA_SYNC` permissions | Large models needed soon after install |
| `on-demand` | When the app asks for it | Same as `fast-follow`; the loader starts the download | Large models used only in an optional feature |
Explain it to users in one sentence per mode and default to `install-time`
when they have no preference. Limits from Play for On-device AI: an AI pack
can be up to 1.5 GB (compressed), an app up to 4 GB; downloads over 200 MB on
mobile data need the user's confirmation, which the generated loader does not
show (it falls back to the CPU model).
## Runtime facts behind the generated files
Fact | Consequence in the package
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------
The Google Tensor NPU runtime is the Maven artifact `com.google.ai.edge.litert:litert-npu-runtime-google-tensor`; its AAR holds `jni/arm64-v8a/libLiteRtDispatch_GoogleTensor.so` and declares `<uses-native-library>` for `libedgetpu_litert.so` and `libedgetpu_util.so` (observed with 2.3.0 and 2.3.2) | The feature module only needs the Maven dependency; no `.so` files or manifest entries are copied by hand
The runtime and `com.google.ai.edge.litert:litert` must be one release | Both versions come from `maven_release` in `versions.json`; the checks and INTEGRATION.md say so
LiteRT's Kotlin API (`litert-api`) is compiled with a recent Kotlin: 2.3.0 and 2.3.2 carry Kotlin metadata 2.4.0, which Kotlin 2.3 reads and Kotlin 2.1 rejects with `was compiled with an incompatible version of Kotlin` (checked 2026-10-14, 2.3.2 on 2026-10-27) | INTEGRATION.md requires Kotlin `kotlin_min` (from `versions.json`) or newer
LiteRT finds the dispatch library by listing the app's native library directory | INTEGRATION.md requires `packaging { jniLibs { useLegacyPackaging = true } }`
AI packs cannot contain native code | The runtime is a feature module, not part of the pack
bundletool requires every module with native libraries to support the same ABIs; LiteRT's own AAR ships more ABIs than the runtime AAR (observed with 2.3.0 and AGP 8.13.1: a base module with `[ARM64_V8A, ARMEABI_V7A, X86_64]` next to the runtime module's `[ARM64_V8A]` fails `packageDebugBundle` with `All modules with native libraries must support the same set of ABIs`) | INTEGRATION.md limits the app to arm64-v8a (`abiFilters`); `--check-project` requires it and marks it risky, because devices without arm64-v8a can then no longer install the app
A module that names a device group the device-targeting XML does not define makes bundletool reject the bundle; all AI packs with group folders must use the same set of groups | The runtime module lists exactly the pack's groups; with several models, package them with the same SoCs
`NpuCompatibilityChecker.GoogleTensor` accepts Android 16 (API 36) or newer, excluding builds whose ID starts with `BP2A` | The loader uses LiteRT's own check plus the packaged SoC list, so older Pixels and builds go straight to the CPU model
`CompiledModel.Options(Accelerator.NPU)` adds the CPU automatically | A partly delegated build still runs in the app (slower); the strict benchmark (step 3) is the gate that catches it
`benchmark_model` uses the `burst` TPU performance mode; LiteRT's Kotlin `CompiledModel.Options` has no Google Tensor options | In-app latency can differ from the benchmark; measure in the app before quoting numbers
The dispatch library in the Maven AAR is a different build than the one in the public binaries bucket that the benchmark downloads, even at the same release (2.3.0, observed 2026-10-14: 579,024 vs 629,984 bytes; the same sizes for Maven 2.3.2 and bucket 2.3.1, 2026-10-27) | To benchmark with the exact library the app ships, pass the AAR: `benchmark_on_device.py --dispatch-lib <litert-npu-runtime-google-tensor-<release>.aar>` (it extracts the `.so`) and say in the report which library was used. The AAR is at `https://dl.google.com/dl/android/maven2/com/google/ai/edge/litert/litert-npu-runtime-google-tensor/<release>/litert-npu-runtime-google-tensor-<release>.aar`, `<release>` being `maven_release`. Observed 2026-10-14 with 2.3.0 on a Pixel 10: the AAR's library passes the strict benchmark and reports TPU tile time, with the same results as the bucket build within run-to-run noise (efficientnet_b7: 26.10 vs 25.61 ms average, 17.75 vs 17.72 ms tile time). If a build's TPU tile time line says `unavailable`, that build has no telemetry hook; the latency rows are still valid. The 2.3.0 AAR's library has the old power hook (checked 2026-10-26: its tile time counts 2 calls per run, corrected by the script), so its **TPU energy** line says `unavailable`; for an app on 2.3.0 the energy comes from runs with the default bucket binaries. The 2.3.2 AAR's library has the fixed hooks (observed 2026-10-27 on a Pixel 10: strict pass, TPU tile time and TPU energy both `1 call per run, one per dispatch invoke`; efficientnet_b7: 26.45 ms average, 17.891 ms tile time, 21.438 mJ energy, vs 26.86 ms, 18.168 ms and 21.643 mJ with the bucket's 2.3.1 library in the next run)
## Checking a package
Before writing, `package_ai_pack.py` checks that each `--compiled` file is
stamped for `Tensor_G5`/`Tensor_G6` with one build per SoC, that `--fallback`
is uncompiled, and that each build matches its `.compile.json` (SHA-256,
target) and was compiled from `--fallback` (only that last check can be
overridden, with `--allow-source-mismatch`). It writes into a staging
directory and never replaces a directory it did not write; `--overwrite`
replaces only its own package.
`package_ai_pack.py` verifies the package before moving it into place (exit 7
otherwise, and nothing is left at `--output-dir`); `pack.json` lists the
checks:
1. The pack folders are exactly one `model#group_Google_Tensor_Gx` per build
plus `model#group_other`.
2. Each packed model is byte-identical to its input and stamped for its
folder's SoC; `model#group_other` holds only the placeholder.
3. The device-targeting XML defines exactly those groups, each with
`system-on-chip manufacturer="Google" model="Tensor Gx"`.
4. The runtime module is delivered to the same groups.
5. The CPU model is byte-identical to `--fallback`.
6. No generated file has an unfilled template placeholder.
On a phone, after the user built and installed the app (INTEGRATION.md,
"Test on a Pixel before releasing"; `install_and_verify.py` does both checks,
see "Checking on a Pixel" below):
- `adb shell pm path <application id>` lists a `google_tensor_runtime` split
on a packaged Pixel (and the pack split for `install-time` delivery).
- `adb logcat -s LiteRtTensor` shows `LITERT_TENSOR_RESULT {"path":"npu", ...}`
when the model runs on the TPU; `"path":"cpu"` comes with `npu_error`.
## Quick test without bundletool (`--quick-test`)
Local testing as Google Play would deliver needs bundletool, because
`./gradlew installDebug` installs the base APK only: no AI pack and no
runtime feature module, so the loader falls back to the CPU model. The
optional quick test avoids that for trying a model on one's own Pixel:
| Piece | What it does |
|---|---|
| `quick_test/<SoC>/assets/model/<model>.tflite` | Copied to `<app module>/tensor_quick_test/`: a copy of each Tensor build (byte-identical, checked) |
| Gradle block in the app module (INTEGRATION.md) | Only with `-PtensorQuickTest=<SoC>`: adds `tensor_quick_test/<SoC>/assets` to the **debug** assets and `litert-npu-runtime-google-tensor` as a `debugImplementation` dependency, so the debug APK itself carries the build at `model/<model>.tflite` and `libLiteRtDispatch_GoogleTensor.so` |
| `TensorModelLoader.kt` | Reads the build from the app's assets when it is there, whatever the delivery mode; otherwise from the AI pack as usual |
Without the property, nothing changes, and release builds never change, so
Google Play users are unaffected. It does not test device-group splitting or
pack delivery: run the bundletool steps before a release. Verified
2026-10-14 on a Pixel 10 with `on-demand` delivery: the debug APK alone ran
the build on the NPU. `--update-project` also replaces existing
`tensor_quick_test/<SoC>/` copies.
## Updating builds an app already ships
`package_ai_pack.py --update-project <project root>` (SKILL.md step 5b) is
for an app that already has a Google Tensor setup - made with this skill,
with LiteRT's NPU guide, or by hand - and gets new builds. Usually only the
model files change; the runtime, device groups, Gradle files and code stay.
### What the script reads
It never writes to the project. It skips comments, `build/` and hidden
folders.
| Piece | How it is found |
|---|---|
| AI pack | A module with an `aiPack { }` (or `assetPack { }`) block and `<folder>#group_<group>/` folders under `src/main/assets`; `packName` and `deliveryType` come from that block. `--pack-name` picks one if several ship Google Tensor builds |
| Model | The `.tflite` in the pack's Tensor group folders (`--model-name` if several). The new builds keep its folder and file name, so the app opens the same path |
| Device groups | The XML named by `deviceTargetingConfig = file(...)` in the module that lists the pack in `assetPacks`. A group belongs to a SoC when its only `system-on-chip` selector is `manufacturer="Google" model="Tensor Gx"`, so the app's own group names work. Without the XML, each folder's build stamp decides |
| CPU copy | `<folder>#group_<defaultGroup>/<file>` in the pack (LiteRT's default layout), `<module>/src/main/assets/litert/<model>_cpu_gpu.tflite` or the loader's `CPU_MODEL_ASSET` (this skill's layout), else `--cpu-asset` |
| Runtime | `com.google.ai.edge.litert:litert-npu-runtime-google-tensor` and `:litert` in the build files (a literal, one `$variable` from the build file or `gradle.properties`, or a `gradle/libs.versions.toml` alias), a local runtime `.aar`, or a bundled `libLiteRtDispatch_GoogleTensor.so`; plus the `<dist:device-group>` list of the module that holds it |
| Loader | A source file with `PACKAGED_SOC_MODELS` (the generated `TensorModelLoader.kt`) for this pack |
### Verdicts
The new files come from LiteRT's exporter, byte-identical to the inputs as
in a new package, and go to `files/<path in the project>`: one per SoC plus
the CPU copy(s). `UPDATE.md` section 2 lists every change beyond them:
| Situation | Verdict | What `UPDATE.md` says |
|---|---|---|
| Same SoCs, same inputs and outputs | `drop-in` | Copy the files; nothing else changes |
| A SoC the app does not ship yet | `structural` | Its group element for the XML (taken from the exporter's XML), a folder in every AI pack with device-group folders (bundletool requires the same groups everywhere), the group in the runtime module's manifest, the SoC in `PACKAGED_SOC_MODELS` |
| A SoC the app ships gets no new build | `structural` | Compile it (recommended), or remove that SoC from the app (folders, group, runtime-module line, loader entry); otherwise its phones keep the previous model |
| Inputs or outputs changed in shape, type or count | `structural` | Update the app's pre- and post-processing. Compared with LiteRT's interpreter on the app's CPU copy and the new original, so only in a real run; changed names alone are `info` |
| No runtime, or `litert` and the runtime at different known releases | `structural` | Add the runtime (a new package has it), or use one release for both |
| The pack also has builds for other SoCs (other vendors) | `structural` | Those builds still hold the previous model |
| The project already has these files | `up-to-date` | Nothing to copy; also the check after copying |
The `Runtime` check compares the app's runtime with `maven_release`: `pass`
when equal, `device` when different or unknown. With `device`, the new
builds must pass the strict benchmark with the app's own library before
release. `benchmark_on_device.py --dispatch-lib` accepts the app bundle
(`.aab`, the library exactly as shipped), the runtime AAR or the `.so`.
Before moving the plan into place, the script checks that every staged file
is byte-identical to its input and stamped for its group's SoC (the CPU copy
uncompiled), and that the project files it plans to replace still have the
SHA-256 it read (exit 7 otherwise).
### Delivering an update
- AI packs ship with app releases: Google Play has no model-only update.
The app bundle needs a higher `versionCode`; Play rejects a reused one.
- `install-time`: the new model arrives with the app update. `fast-follow`
and `on-demand`: the app update invalidates packs downloaded before; Play
downloads `fast-follow` packs again right after the update, and
`on-demand` packs when the app requests them (the generated loader does,
and uses the CPU model until then).
- bundletool local testing cannot update an installed app: uninstall first.
## Applying the plan (SKILL.md step 6)
The agent applies a package or an update to the user's project only after
the user says yes: one approval for the whole plan, then a separate OK for
each risky item. The scripts never write to the project; the agent copies
the files and edits the build files itself. For an update, the plan is
`UPDATE.md`, and the dry run of `--update-project` must report every file
`unchanged` afterwards.
### New integration (6a)
1. Ask for the project root (the folder with `settings.gradle.kts` or
`settings.gradle`). If it is a git checkout with uncommitted changes
(`git status --porcelain`), say so in the plan and suggest committing
first.
2. Get the plan (read-only, any `python3`, no LiteRT):
`python3 scripts/package_ai_pack.py --check-project <project root>
--package <output-dir of step 5a> [--app-module app] [--json]`. Every
requirement of `INTEGRATION.md` comes back as `pass`, `fail` or `warn`
(checks below). The `fail` items are the plan; offer the `warn` items (for
example the optional quick test) as options.
3. Show the plan once: the files to copy, the files to edit with their
snippets, and the risky items marked. Get the approval, then the separate
OKs.
4. Apply it: run the copy commands; make the edits with your file-editing
tool, merged into the existing blocks (`android { }`, `defaultConfig`,
`dependencies`, the version catalog when the project uses one) in the
file's own style. Never delete or reformat unrelated code, and never touch
signing configs.
5. Re-run step 2 until nothing fails (apart from declined items).
6. Build once from the project root: `./gradlew :<app module>:bundleDebug`.
Fix errors your edits caused; report errors that were there before instead
of fixing them.
7. Report what changed, and how the app uses the model: `INTEGRATION.md` step
9 has the loader call, `model_io.json` the inputs and outputs. If the user
tells you where the model is used, offer to write that code (the pre- and
post-processing depend on their app, so show it first). Then offer
SKILL.md step 7.
`--check-project` compares the project with every requirement of the
package's `INTEGRATION.md`. It reads the project like `--update-project`
(skipping comments, `build/` and hidden folders), needs no LiteRT and
writes nothing. Each check is `pass`, `fail` or `warn`. A `fail` comes with
its fix - `copy` (a shell command that copies from the package) or `edit`
(the file, and a snippet in the project's Kotlin or Groovy DSL) - and is
`risky` when it needs its own OK. `--json` prints the same as one object
(`checks`, `summary.to_do`, `summary.risky`). "The package's release" below
is the LiteRT release in its `pack.json` (`maven_release` when it was
written).
| Check | Passes when | Risky when it fails because |
|---|---|---|
| AI pack module | `ai_packs/<pack>/` holds every file of the package, byte-identical, and its build file sets the package's `packName` and `deliveryType` | Project files differ from the package (they would be replaced) |
| Runtime modules | `litert_npu_runtime_libraries/google_tensor_runtime/` and `.../runtime_strings/` exist; the runtime module names no other runtime release or app module, and its manifest delivers it to the pack's device groups | - |
| Device-targeting XML | The XML named by the app's `deviceTargetingConfig` (else `<app>/device_targeting_configuration.xml`) defines the package's groups with the same selectors | - |
| CPU model | `<app>/src/main/assets/litert/<model>_cpu_gpu.tflite` is the package's original model | Another file is there |
| Model loader | A `TensorModelLoader.kt` for this pack opens `model/<model>.tflite` with the package's delivery mode and SoC list | It exists but differs (it would be replaced) |
| Quick test (optional) | Only for `--quick-test` packages: the copies in `<app>/tensor_quick_test/` and the Gradle block are there; at most `warn` | - |
| Settings includes | `settings.gradle(.kts)` includes the pack and both runtime modules | - |
| App: `assetPacks`, `dynamicFeatures` | The app module lists the pack and the runtime module | - |
| App: bundle device targeting | `bundle { deviceTargetingConfig = file(...) ; deviceGroup { enableSplit = true ; defaultGroup = "other" } }` | - |
| App: native libraries extracted | `useLegacyPackaging = true`, or `android:extractNativeLibs="true"` in the manifest | - |
| App: `minSdk` | 31 or higher (`warn` when the app's build file does not set it, e.g. a convention plugin does) | It is below 31: phones below Android 12 could no longer install the app |
| App: ABI filters | `abiFilters` names `arm64-v8a` only (`warn` when it is set from a value the check cannot read) | It is missing or names other ABIs: devices without arm64-v8a could no longer install the app |
| App: LiteRT dependency | `com.google.ai.edge.litert:litert` at the package's release (`warn` when the version cannot be read) | The app uses another LiteRT release |
| App: `runtime_strings` dependency | The app module depends on the `runtime_strings` module | - |
| `gradle.properties` | `android.experimental.enableDeviceTargetingConfigApi=true` | - |
| App: download permissions | Only for `fast-follow` / `on-demand`: `FOREGROUND_SERVICE` and `FOREGROUND_SERVICE_DATA_SYNC` are declared | - |
| Android Gradle plugin | 8.10 or newer (`warn` when the version is not found) | It is older: the upgrade affects the whole build |
| Kotlin | The Kotlin Android plugin at `kotlin_min` of the package or newer (`warn` when the version is not found, or with AGP 9 or newer when no plugin is applied) | It is older, or the app has no Kotlin |
Exit 0 means nothing is left to do, which is also the proof after applying;
exit 1 lists the work; exit 2 is bad input (no project, no package, no app
module). Not checked: the app code that calls the loader (where the app uses
the model is the app's choice) and signing configs, which the agent never
touches.
### Update (6b)
The plan is `UPDATE.md`: the file table and section 2. Get one approval for
the files and the non-risky edits, and separate OKs for the risky ones
(removing a SoC, changing the runtime or LiteRT version, replacing a loader
with local changes; changed model inputs or outputs need app code changes, so
show that code first). Then: copy each project file you replace to
`<output-dir>-backup/<path>` (not inside `<output-dir>`, which `--overwrite`
replaces), copy `files/<path>` to `<project>/<path>`, make the section 2
changes, and raise `versionCode`. Re-run the step 5b command with `--dry-run`:
every file must show `unchanged`. Build once (as in 6a, step 6), then offer
SKILL.md step 7.
## Checking on a Pixel (SKILL.md step 7)
`./gradlew installDebug` cannot test the package: it installs no AI pack and
no feature module. `install_and_verify.py --project <project root>`
installs the app the way Google Play would, with bundletool's local testing:
1. It finds the app module (the only one that applies
`com.android.application`, or `--app-module`), its device-targeting XML
and the group of each Google Tensor SoC; the Android SDK (`--sdk`,
`ANDROID_HOME`, `ANDROID_SDK_ROOT`, `local.properties`, the default
folders), adb, Java (`JAVA_HOME`, else `java` on PATH), the project's
`./gradlew` (or `--gradle`) and the newest `aapt2` in the SDK.
2. It reads the phone's model, SoC (`ro.soc.model`), API level and build ID,
picks the device group of that SoC, and says whether LiteRT will use the
NPU there (the conditions of `NpuCompatibilityChecker` above). `--dry-run`
stops here and downloads nothing.
3. It builds `:<app>:bundleDebug` (`--variant` picks another variant, e.g.
`release` or a product-flavor variant such as `freeDebug`) and reads the
application id from the bundle. If that app is already installed, it
stops here with exit 7 (local testing cannot update an app); with
`--uninstall-first` it uninstalls it once the new APK set is built.
4. It runs `bundletool build-apks --local-testing` and `install-apks
--device-groups=<group>`: what Google Play would install on this phone,
including the AI pack and the runtime feature module.
5. It lists the installed splits (`pm path`) and checks for
`libLiteRtDispatch_GoogleTensor.so` in the app's native library folder.
6. It starts the launcher activity and waits for the loader's
`LITERT_TENSOR_RESULT` line in the app process's log.
bundletool is `--bundletool` (a `bundletool-all` jar, or a folder of
bundletool jars), else `bundletool-all-<bundletool_release>.jar` from
https://github.com/google/bundletool/releases, cached in
`~/.cache/litert-google-tensor/`. The output folder (`--output-dir`, default
`./litert_app_verify/<timestamp>/`) holds `results.json`, `report.md` and
the Gradle and bundletool logs; the `.apks` file is deleted unless
`--keep-apks`. The app stays installed. The script never signs for release
or uploads, and uninstalls an installed copy only with `--uninstall-first`.
| Result | Meaning |
|---|---|
| `"path":"npu"`, exit 0 | The Tensor build ran on the TPU, installed as Google Play would install it |
| `"path":"cpu"` where the NPU is not expected, exit 0 | The correct fallback: no build for the phone's SoC, Android below API 36, or a `BP2A` build (the report's `Expected path: CPU (...)` says which) |
| `"path":"cpu"` on a phone with a build, exit 1 | Part of the setup is missing: the `npu_error`, the installed splits and the dispatch-library line say which (`troubleshooting.md`) |
| No result line, exit 6 | The app did not call `TensorModelLoader.load()` within `--timeout` (it may load the model on another screen), or it crashed |
The script needs a JDK the project's Gradle supports (`JAVA_HOME`), the
Android SDK (adb), the project's `./gradlew` (or `--gradle`, which may carry
options such as `-Pname=value`), and a Pixel with USB debugging. Run
`--dry-run` first; an app with product flavors needs `--variant` (for example
`freeDebug`). Exit codes: 0 ran on the NPU (or on the CPU where no Tensor
build is expected; with `--no-launch`: installed), 1 CPU on a phone with a
Tensor build, 2 environment (project, tools, device), 3 Gradle build failed,
4 bundletool failed, 6 no result line, 7 already installed. After exit 7, ask
the user before rerunning with `--uninstall-first` (uninstalling deletes the
app's data on the phone); after exit 6, have the user open the screen that
loads the model while the script waits, or raise `--timeout`.
## Public references
- LiteRT NPU guide (AI packs, runtime modules, `CompiledModel`):
https://developers.google.com/edge/litert/next/npu
- Play for On-device AI (AI packs, delivery modes, device targeting, local
testing): https://developer.android.com/google/play/on-device-ai
- Play Feature Delivery: https://developer.android.com/guide/playcore/feature-delivery
- LiteRT Kotlin API (`AiPackModelProvider`, `ModelSelector`, ...):
https://developers.google.com/edge/api/litert/kotlin
- LiteRT's AI-pack exporter source:
https://github.com/google-ai-edge/LiteRT/blob/main/litert/python/aot/ai_pack/export_lib.py
- bundletool: https://github.com/google/bundletool/releases
- Google Maven (`com.google.ai.edge.litert`):
https://maven.google.com/web/index.html#com.google.ai.edge.litert
benchmark-flags.md 49.3 KB
# On-device benchmarking reference
`scripts/benchmark_on_device.py` drives LiteRT's `benchmark_model` tool
(public docs: https://developers.google.com/edge/litert/next/benchmark) over
adb. This page lists the exact flags it uses, what the tool prints, and where
the two binary dependencies come from.
## Contents
- [What the script does](#what-the-script-does): Lines 28-80
- [Files pushed to the phone](#files-pushed-to-the-phone): Lines 82-174
- [The public binaries bucket](#the-public-binaries-bucket): Lines 111-136
- [Other ways to get `libLiteRtDispatch_GoogleTensor.so`](#other-ways-to-get-liblitertdispatch_googletensorso): Lines 138-156
- [Choosing binary versions](#choosing-binary-versions): Lines 158-174
- [Flags used](#flags-used): Lines 176-216
- [NPU run (strict, the default)](#npu-run-strict-the-default): Lines 178-205
- [CPU baseline run (`--cpu-baseline <original.tflite>`)](#cpu-baseline-run---cpu-baseline-originaltflite): Lines 207-216
- [TPU tile time](#tpu-tile-time): Lines 218-294
- [TPU energy](#tpu-energy): Lines 296-346
- [Output format parsed by the script](#output-format-parsed-by-the-script): Lines 348-440
- [Log lines that are expected (benign)](#log-lines-that-are-expected-benign): Lines 396-421
- [Profiler summary vs. the table](#profiler-summary-vs-the-table): Lines 423-440
- [Writing the report](#writing-the-report): Lines 442-510
- [Example script output (one real run; never reuse these numbers)](#example-script-output-one-real-run-never-reuse-these-numbers): Lines 512-691
- [Example with TPU tile time and energy (real run; never reuse the numbers)](#example-with-tpu-tile-time-and-energy-real-run-never-reuse-the-numbers): Lines 641-691
- [Accuracy notes](#accuracy-notes): Lines 693-699
## What the script does
In order:
1. Selects the device, reads `ro.soc.model`, and refuses to run a model
compiled for another SoC (exit 4, before anything is downloaded or pushed;
`--allow-mismatch` overrides). `--dry-run` skips this - it never contacts
the device - so a dry run proves nothing about the SoC match.
2. Resolves `benchmark_model` and `libLiteRtDispatch_GoogleTensor.so` (local
copies, else one-time downloads from the public bucket, cached; sources,
cache and provenance records: "Files pushed to the phone" below) and prints
where each came from. `downloaded from <url>` means this was the first
time - tell the user what was fetched; `fetch date not recorded` marks a
copy cached by an older version of the script (`--refresh-binary`
re-downloads it and records the fetch).
3. Pushes them with the model to a fresh
`/data/local/tmp/litert_benchmark/run-<timestamp>-<pid>/` (`--device-dir`
changes the base). Files already on the phone are never overwritten or
deleted. Leftovers from an interrupted run are therefore always
`<base>/run-*`: if the user asks to clean up, `adb shell ls -la <base>`
first and remove only `run-*` entries (never the base or anything else in
it).
4. Reads the thermal status (`dumpsys thermalservice`), then runs the NPU
benchmark in strict mode (flags under "Flags used" below), retrying once
without the profiler if that run fails.
5. Runs the same NPU benchmark once more, without profiler and memory monitor,
with `LITERT_VENDOR_HOOK_ARGS` pointing at a hook config in the run
directory that enables the TPU tile-time and power metrics, and divides the
hooks' totals (`Total TPU tile time`, `Total Energy`) by that pass's own
warmup + measured runs. The hooks' own counts are only checks: older
dispatch libraries count every inference 1 + D times (D = dispatch nodes, so
2x for a normal compiled model), which is why the hooks' `Average` lines are
never used; an old power hook is not used at all (the script checks the
library first). Checks and evidence: "TPU tile time" and "TPU energy"
below.
6. Optionally runs the CPU baseline on the **uncompiled** model
(`--use_cpu=true`, same run counts).
7. Prints the Markdown header + table, writes `results.json`, `report.md` (the
same block as a file), `npu.log`, `tile_time.log` (the hooked pass, + the
hooks' `tile_time_report.txt` and `power_report.txt`), `cpu.log`,
`npu_profile.txt`, `cpu_profile.txt`, and deletes the per-run device
directory (even on failure). `--output-dir` is only created once a benchmark
actually ran - after exit 2/3/4 or `--dry-run` there are no logs to look
for.
Useful options (all in `--help`): `--num-runs`, `--warmup-runs`, `--signature`,
`--performance-mode
{extreme_power_saver,power_saver,balanced,high_performance,sustained_performance,burst}`
(benchmark default `burst`), `--cpu-num-threads`, `--extra-arg=--min_secs=5`
(extra `benchmark_model` flags; they cannot switch the accelerator),
`--device-dir`, `--benchmark-bin` + `--dispatch-lib` (local copies, offline),
`--serial`, `--allow-cpu-fallback`, `--keep-device-files`, `--refresh-binary`,
`--no-tile-time`, `--no-power`, `--dry-run`.
## Files pushed to the phone
Everything goes to a fresh per-run directory
`/data/local/tmp/litert_benchmark/run-<timestamp>-<pid>/` (base overridable
with `--device-dir`) and only that directory is deleted afterwards (unless
`--keep-device-files`). Files that were already in the base directory - e.g.
your own `benchmark_model` or models from earlier manual runs - are never
overwritten or removed; the base directory itself is removed only if the run
created it.
File | Purpose | Source
----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------
`benchmark_model` | android_arm64 LiteRT benchmark binary | `--benchmark-bin`, else downloaded once from `--benchmark-url` (default `https://storage.googleapis.com/litert/binaries/<release>/android_arm64/benchmark_model`, `<release>` = `binaries_release` in `versions.json`; `--help` prints the resolved URL).
`libLiteRtDispatch_GoogleTensor.so` | Google Tensor dispatch (NPU runtime) library loaded through `--dispatch_library_path` | `--dispatch-lib`, else `$LITERT_GOOGLE_TENSOR_DISPATCH_LIB`, else downloaded once from `--dispatch-url` (default: `libLiteRtDispatch_GoogleTensor.so` in the same directory as `--benchmark-url`).
`<model>.tflite` | the compiled model (and the uncompiled one for `--cpu-baseline`) | user
`tpu_hooks.textproto` | config of the hooked pass (TPU tile-time and power metrics); the hooks write their reports to `tpu_tile.txt` and `tpu_power.txt` next to it | written by the script (not with both `--no-tile-time` and `--no-power`)
Downloads are cached in `~/.cache/litert-google-tensor/` (override with
`LITERT_GOOGLE_TENSOR_CACHE`; `--refresh-binary` re-downloads) under the name
`<release>_android_arm64_<file>`, `<release>` being the bucket directory the
file came from (e.g. `latest_android_arm64_benchmark_model` for a
`--benchmark-url` under `binaries/latest/`). Next to each
download, `<file>.json` records the URL, the UTC fetch time, size, SHA-256 and
the bucket's `x-goog-generation` / md5 / crc32c response headers; the
provenance lines show the fetch time and md5 from it. A cached copy of a
rolling release stays the build that was first downloaded, and that md5 is
what identifies it. The dispatch library links against the TPU driver that
ships on the Pixel itself, so nothing else needs to be pushed.
### The public binaries bucket
`https://storage.googleapis.com/litert/binaries/<release>/android_arm64/` holds
prebuilt LiteRT tools and runtime libraries built together from one release, so
`<release>` is the unit of versioning. The skill's default release is
`binaries_release` in `versions.json`. Known contents (bucket listing checked
2026-10-26):
`<release>` | `benchmark_model` | `libLiteRtDispatch_GoogleTensor.so`
------------------------------------- | ----------------- | -----------------------------------
`latest`, `nightly`, `2.3.0`, `2.3.1` | yes | yes
`2.1.6`, `2.2.0` | yes | **no** - the download 404s; supply `--dispatch-lib`
`latest/` is not a copy of the newest numbered directory: on 2026-10-07 its
`benchmark_model` and dispatch library had different sizes and md5s than
`2.3.0/`'s. The directory listing (with each object's `md5Hash`) is public:
`https://storage.googleapis.com/storage/v1/b/litert/o?prefix=binaries/latest/android_arm64/`.
A numbered directory can be re-uploaded too. `2.3.1/` was first uploaded on
2026-10-20 with a dispatch library byte-identical to `2.3.0/`'s (md5
`VuNepRvYbhpk4UjeRM2JvA==`, still with the double-counting hook described under
"TPU tile time"), then replaced on 2026-10-23 17:54 UTC by a rebuild with the
hook fix (md5 `tp26wryZhjaU3IYIz2w7/g==`; its `benchmark_model` was rebuilt too,
with only the build stamp changed). A cache filled before a re-upload keeps the
old build under the same file name: when a provenance line's md5 differs from
`verified.binaries` in `versions.json`, rerun with `--refresh-binary`.
### Other ways to get `libLiteRtDispatch_GoogleTensor.so`
1. **GitHub release assets** - `litert_npu_runtime_libraries.zip` under
https://github.com/google-ai-edge/LiteRT/releases. `--dispatch-lib` accepts
the `.zip` (or an `.aar`, which is also a zip) and extracts the `.so`,
preferring an `arm64-v8a`/`arm64` entry when several exist.
2. **Build from source** - follow "How do I build a Google Tensor dispatch
library?" in https://developers.google.com/edge/tensor-sdk/tensor-faqs
(Bazel target `litert/vendors/google_tensor/dispatch:dispatch_api.so`).
Whatever the source, prefer the dispatch library and `benchmark_model` from the
same LiteRT release (the default does this). Nearby releases do interoperate
(`latest` binary + `2.3.0` library and the reverse both ran fine on a Pixel 10);
a far-apart pair is the first thing to suspect if the run dies right after the
`Loading shared library: .../libLiteRtDispatch_GoogleTensor.so` line. Compiler
and runtime releases can differ too: a model compiled with ai-edge-litert 2.1.6
ran fully delegated on the `2.3.0` binaries (Pixel 10, 2026-10-07) and on the
`2.3.1` binaries (2026-10-26); the report's **Versions** line shows which pair a
run used.
### Choosing binary versions
Keep `benchmark_model` and the dispatch library from the **same** release
directory of the bucket (the default does: both come from `binaries_release` in
`versions.json`); pass
`--benchmark-url .../binaries/<release>/android_arm64/benchmark_model` to pin
another one and the dispatch URL follows. A rolling directory (`latest/`,
`nightly/`) changes over time, but a cached copy stays the build that was first
downloaded until `--refresh-binary`; the md5 in its provenance line tells builds
apart. A numbered directory can be re-uploaded as well (bucket notes above): if
a provenance md5 differs from `verified.binaries` in `versions.json`, rerun with
`--refresh-binary`. Local files carry no version string the script could
compare, so for `--benchmark-bin`/`--dispatch-lib` the rule is "both from the
same download"; if that is uncertain, re-download both from one directory. Not
every versioned directory ships the Google Tensor dispatch library (which ones
do: the bucket table above) - if the download 404s, use the default URLs or
supply `--dispatch-lib` from one of the other sources above.
## Flags used
### NPU run (strict, the default)
```text
benchmark_model --graph=<model> --use_npu=true --use_cpu=false
--require_full_delegation=true
--dispatch_library_path=/data/local/tmp/litert_benchmark/run-<id>
--num_runs=50 --warmup_runs=5
--report_peak_memory_footprint=true --use_profiler=true
[--signature_to_run_for=<key>]
[--google_tensor_performance_mode=<mode>]
```
| Flag | Default in tool | Why the skill sets it |
|---|---|---|
| `--use_npu` | `false` | Select the NPU accelerator. |
| `--use_cpu` | `true` | Must be `false` together with `--require_full_delegation=true`; the tool aborts with "Requesting full delegation and CPU acceleration are incompatible" otherwise. |
| `--require_full_delegation` | `false` | Fail instead of silently timing CPU fallback ops. `--allow-cpu-fallback` removes this pair. |
| `--dispatch_library_path` | `""` | Directory containing `libLiteRtDispatch_GoogleTensor.so`. |
| `--num_runs` / `--warmup_runs` | `50` / `1` | Skill uses 50 / 5 (`--num-runs`, `--warmup-runs`). These are **minimums**: the tool also runs for at least `--min_secs` (default 1.0 s) and warms up for at least `--warmup_min_secs` (default 0.5 s), so a fast model reports more runs than requested (e.g. a 15 ms model: 65 measured / 31 warmup). The "Runs" row shows the actual counts. For exact counts add `--extra-arg=--min_secs=0 --extra-arg=--warmup_min_secs=0`. |
| `--report_peak_memory_footprint` | `false` | Adds "Peak memory" to the results (`--no-peak-memory` to disable). |
| `--use_profiler` | `false` | Enables runtime profiling; the summary is saved to `npu_profile.txt`. For a fully delegated model it shows one `DELEGATE` node, not TPU-internal ops. If the profiled run fails the script retries once without it. |
| `--google_tensor_performance_mode` | `burst` (set by the tool when `--use_npu`) | `--performance-mode` one of `extreme_power_saver`, `power_saver`, `balanced`, `high_performance`, `sustained_performance`, `burst`. |
| `--signature_to_run_for` | `""` | Multi-signature models (`--signature`). |
Other upstream `benchmark_model` flags (`--min_secs`, `--max_secs` (default 150
s), `--warmup_min_secs`, `--input_layer_value_range`, ...) can be appended with
`--extra-arg=--flag=value` (NPU run and hooked pass; the CPU baseline keeps the
defaults so the two columns stay comparable).
### CPU baseline run (`--cpu-baseline <original.tflite>`)
```text
benchmark_model --graph=<original> --use_cpu=true --num_runs=50 --warmup_runs=5
--report_peak_memory_footprint=true --use_profiler=true
[--num_threads=N]
```
The baseline must be the **uncompiled** model: a compiled model's TPU
partitions are `DISPATCH_OP` custom ops that the CPU cannot execute.
## TPU tile time
On by default (`--no-tile-time` skips it) and never fails the job: a problem
shows up in the header line as `unavailable`, `failed`, `no report` or
`inconsistent` with the reason, the table row shows `-`, and the latency numbers
are unaffected.
After the NPU run the script runs `benchmark_model` once more with the NPU flags
minus `--use_profiler=true` and `--report_peak_memory_footprint=true`, prefixed
with `LITERT_VENDOR_HOOK_ARGS=<run dir>/tpu_hooks.textproto`. This hooked pass
also measures the TPU energy (next section); its config holds one block per
metric (`--no-tile-time` or `--no-power` drops one, both together skip the
pass):
```text
tpu_tile_time_metrics_config {
dump_tpu_tile_time_metrics: true
tpu_tile_time_metrics_dump_path: "<run dir>/tpu_tile.txt"
}
power_config {
dump_power_metrics: true
power_dump_path: "<run dir>/tpu_power.txt"
}
```
`libLiteRtDispatch_GoogleTensor.so` adds up `hardware_execution_time_us` (pure
TPU execution time) of every dispatch invoke and, when the model is torn down,
writes a report (saved as `tile_time_report.txt`; the same block is logged at
INFO level, which the script uses if the file is missing). The `2.3.1` library
(re-upload of 2026-10-23) wrote this one in the run of the example below:
```text
==== Google Tensor TPU Tile Time Metrics ====
Total inferences: 66
Total TPU tile time (us): 1169131
Average TPU tile time (us): 17714.11
Min TPU tile time (us): 17466
Median TPU tile time (us): 17698.00
P95 TPU tile time (us): 17865
==================================
```
Older libraries (`2.3.0`, and `2.3.1` as first uploaded on 2026-10-20) write
only the first three numbers, and their `Total inferences` and `Average` are
wrong: each inference reaches the hook 1 + D times (once from the LiteRT
runtime's `Run`, once per dispatch invoke; D from
`Replacing D out of M node(s)`), but only the dispatch calls add tile time. For
the same model, the `2.3.0` library reported `Total inferences: 144` and
`Average TPU tile time (us): 8844` for 72 runs (2026-10-09), half the real
17.689 ms. With either kind of library the script reports
`Total TPU tile time / (warmup + measured runs of this pass)` (above: 1169131 us
/ 66 runs = 17.714 ms), uses the hook's count only as a check, and does not copy
the `Min`/`Median`/`P95` lines into the report:
`Total inferences` / runs | Meaning | Result
------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ------
D (1 for a normal compiled model) | one call per dispatch invoke (`2.3.1` re-upload, observed 2026-10-26; `nightly`, 2026-10-23; Maven `2.3.2` AAR, 2026-10-27) | per inference = total / runs
1 + D (2 for a normal compiled model) | the double count (`2.3.0` binaries, observed 2026-10-09; first `2.3.1` upload, 2026-10-23; Maven `2.3.0` AAR, 2026-10-26) | same
1 | the hook counts runs | same
anything else | unexplained, e.g. a multi-signature model whose first `Replacing` line belongs to another subgraph | `inconsistent`: totals only
- The pass's own latency is not reported: the hook adds about 3% per inference
(+0.77 ms on a 23.7 ms model, mean of 3 interleaved pairs, Pixel 10,
2026-10-09). Its run counts can differ from the NPU run's (time floors), so
the tile time uses its own pass's counts.
- `tile_time.log` status lines:
`Successfully retrieved and registered vendor hooks in CompiledModel.` =
hook active; `Accelerator returned null hooks.` = the dispatch library has
no hooks. Builds from the LiteRT GitHub source compile them out; the
Google-built bucket libraries have them (checked for `2.3.0` and `latest` on
2026-10-09, `2.3.1` on 2026-10-26), and so do the libraries in the Maven
`litert-npu-runtime-google-tensor` AARs (`2.3.0` on 2026-10-14, `2.3.2` on
2026-10-27).
- The hook parses its config by substring after stripping all whitespace: only
lowercase `true` enables a metric, a commented-out key still counts, and the
dump paths cannot contain whitespace (the script refuses such a
`--device-dir`).
## TPU energy
On by default (`--no-power` skips it) and, like the tile time, never fails the
job. The `power_config` block above turns on the dispatch library's power metric
in the same hooked pass: the energy counter of the TPU rail in the phone's
on-device power monitor. The fixed hook (the `2.3.1` library as re-uploaded on
2026-10-23, and the library in the Maven `2.3.2` AAR) reads that counter when
the first dispatch invoke starts and again when the model is torn down, counts
dispatch invokes, and writes this report (saved as `power_report.txt`; the same
numbers are logged at INFO level, which the script uses if the file is missing),
from the run of the example below:
```text
Average TPU Energy consumed per inference(uJ): 21279.485
Total Energy (uJ): 1404446
Inference count: 66
```
The script reports `Total Energy / (warmup + measured runs of the pass)` as
**TPU energy / inference (mJ)** (here 1404446 uJ / 66 runs = 21.279 mJ) and uses
the hook's count only as a check. The total spans the whole pass, so the value
includes the TPU's energy in the idle gaps of the benchmark loop and at
teardown: it is the energy per inference of back-to-back inference, for
comparing models, builds and performance modes on the same phone, not a lab
measurement of one isolated inference. It is measured with the tile-time metric
on; `--no-tile-time` gives a power-only pass (21.474 vs 22.076 mJ for the
example model in two single runs, 2026-10-26).
`Inference count` / runs | Meaning | Result
------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------
D (1 for a normal compiled model) | one call per dispatch invoke (`2.3.1` re-upload, observed 2026-10-26; Maven `2.3.2` AAR, 2026-10-27) | per inference = total / runs
1 + D (2 for a normal compiled model) | the old power hook (`2.3.0` and the first `2.3.1` upload, observed 2026-10-23) | `unreliable`: no value
anything else | unexplained | `inconsistent`: totals only
- The old power hook reads the counter around every call. With the example
model that slowed inference from about 24 ms to 102.54 ms, and its per-call
windows caught 56,700 uJ for 56 runs, where the fixed hook's 21.7 mJ per
inference would make about 1.2 million (2026-10-23). The script therefore
checks the dispatch library before the pass: if it contains the old hook's
log string `failed HandlePowerRuntimeStop`, the power metric stays off and
the header says `unavailable` (the Maven `litert-npu-runtime-google-tensor`
2.3.0 AAR has the old hook, checked 2026-10-26; the 2.3.2 AAR has the fixed
one, 2026-10-27). The count check catches an old hook the string check
misses (`unreliable`).
- `unavailable - the power hook could not read the TPU energy counter:
'<line>'` quotes the hook's own log line
(`Google TensorHook failed HandlePowerRuntimeStart: ...` or
`Skipping power metrics dump ...`): the phone did not let the shell process
read its power monitor. Latency and tile time are unaffected.
- With the fixed hook the power metric adds no per-inference work (it only
counts), so it does not slow the pass.
## Output format parsed by the script
Recent LiteRT binaries print a results block like this one (verbatim from an
earlier Pixel 10 run; the `2.3.0` and `2.3.1` binaries print the same format,
checked 2026-10-07 and 2026-10-26; the parser strips the `INFO: [file:line]`
prefixes):
```text
INFO: Running benchmark for at least 5 iterations and at least 0.5 seconds but terminate if exceeding 150 seconds.
INFO: count=31 first=14065 curr=17133 min=11374 max=17700 avg=15934.7 std=1771 p5=11961 median=16478 p95=17661
INFO: Running benchmark for at least 50 iterations and at least 1 seconds but terminate if exceeding 150 seconds.
INFO: count=65 first=16308 curr=17045 min=10667 max=17784 avg=15125.2 std=2501 p5=11016 median=16621 p95=17564
INFO: [benchmark_litert_model.h:89]
========== BENCHMARK RESULTS ==========
INFO: [benchmark_litert_model.h:92] Signature name: <placeholder signature>
INFO: [benchmark_litert_model.h:94] Model initialization: 502.36 ms
INFO: [benchmark_litert_model.h:96] Warmup (first): 14.06 ms
INFO: [benchmark_litert_model.h:98] Warmup (avg): 15.93 ms (31 runs)
INFO: [benchmark_litert_model.h:100] Inference (avg): 15.13 ms (65 runs)
INFO: [benchmark_litert_model.h:104] Inference (min): 10.67 ms
INFO: [benchmark_litert_model.h:106] Inference (max): 17.78 ms
INFO: [benchmark_litert_model.h:108] Inference (std): 2.50
INFO: [benchmark_litert_model.h:115] Throughput: 49.59 MB/s
INFO: [benchmark_litert_model.h:124]
Memory Usage:
INFO: [benchmark_litert_model.h:126] Init footprint: 80.24 MB
INFO: [benchmark_litert_model.h:128] Overall footprint: 80.99 MB
INFO: [benchmark_litert_model.h:132] Peak memory: 124.37 MB
INFO: [benchmark_litert_model.h:138] ======================================
<profiler summary when --use_profiler=true: one DELEGATE node for a fully compiled model>
```
The two `Running benchmark for at least ...` lines show the time floors
(`--warmup_min_secs`, `--min_secs`) that made this 15 ms model run 31 / 65
times instead of the requested 5 / 50. Each is followed by a per-phase stats
line in **microseconds** (`count=... min= max= avg= std= p5= median= p95=`);
the first is the warmup phase, the second (its `count=` equals the measured
run count) is the measured phase, and it is the only place percentiles
appear. The script converts its `p5`/`median`/`p95` to ms for the
`Inference p5 / p50 / p95 (ms)` table row and `results.json`
(`inference_p5_ms`, `inference_p50_ms`, `inference_p95_ms`). Earlier in the
log, `Replacing 1 out of 1 node(s) with delegate (DispatchDelegate)` confirms
full delegation (the script copies it into the `Delegation (runtime)` header
line), and `Loading shared library: .../libLiteRtDispatch_GoogleTensor.so`
confirms which dispatch library was used.
### Log lines that are expected (benign)
Seen in every successful strict run on a Pixel 10; do not report them as
problems:
Line | Meaning
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------
`WARNING: [compiled_model.cc:815] Compiler plugin path is provided in the environment, but the model is pre-compiled. Plugins won't be applied.` | Normal for an AOT-compiled model: there is nothing left to compile on device.
`WARNING: [dispatch_delegate_kernel.cc:793] MediaTek dispatch API returned contradictory buffer requirements for Float32 tensor ...: expected size=8 bytes / But dispatch API returned: 64 bytes` | Buffer-size padding reported by shared dispatch-delegate code; the "MediaTek" wording is a mislabel on Google Tensor. Seen with tiny tensors; the run completes and the results are valid.
`INFO: [litert_dispatch.cc:186] Loading shared library: .../libLiteRtDispatch_GoogleTensor.so`, `SouthBound context created.`, `SouthBound symbols resolved by 'libedgetpu_litert.so'`, `Found GoogleTensorOptions` | The Google Tensor dispatch library loaded and bound to the on-device TPU driver.
`VERBOSE: Replacing N out of N node(s) with delegate (DispatchDelegate) node, yielding 1 partitions ...` | Full delegation. `N out of M` with N < M would mean CPU fallback (strict mode then fails).
`INFO: [compiled_model.cc:1065] Accelerator returned null hooks.` | Informational in `npu.log` / `cpu.log` (no hook configured there). In `tile_time.log` it means the dispatch library has no telemetry hooks, and TPU tile time is `unavailable`.
`INFO: [compiled_model.cc:1056] Successfully retrieved and registered vendor hooks in CompiledModel.`, the `==== Google Tensor TPU Tile Time Metrics ====` block, `Google TensorHook: TPU metrics dumped to ...`, `Power hook has generated following data:` with its three lines, `Google TensorHook: Power metrics dumped to ...` | `tile_time.log` only: the hooks are active and wrote their reports (INFO level, so the Log check does not count them).
A line that is **not** benign: the run ending right after `Loading shared
library:` with no `Replacing ...` line (unusable dispatch library), or
`Failed to invoke SB invocation context` / `Node number 1 (DELEGATE) failed to
invoke` (model compiled for another SoC, see `troubleshooting.md`).
`benchmark_on_device.py` applies this list itself: the two WARNING patterns
above are counted as `known-benign` in the report's **Log check** line, and
every other WARNING/ERROR-level line (including the abseil-style `E0000 ...`
lines of the TPU driver) is listed verbatim under **Unexpected log lines**
(see the example output below). Treat a non-zero unexpected count as
something to explain in the report's Notes, not as an automatic failure - the
table values are still real if `benchmark_model` exited 0.
### Profiler summary vs. the table
With `--use_profiler=true` the log ends with a per-op table containing a
single `DELEGATE` row for a fully compiled model. Its `[avg ms]` covers only
the delegate invoke and is lower than the table's `Inference (avg)`, which
also includes input/output buffer handling. Report the table value; the
profile is saved to `npu_profile.txt` for reference only.
Older binaries print the upstream TFLite one-liner instead
(`Inference timings in us: Init: ..., First inference: ..., Warmup (avg): ...,
Inference (avg): ...` and `Overall peak memory footprint (MB) via periodic
monitoring: ...`); the parser understands both. Raw logs are always kept in the
output directory (`npu.log`, `cpu.log`). A binary that exits 0 but prints
neither format (and none of the crash markers such as `Benchmarking failed`)
stops the script with exit 6 `... printed no results in the format this
script parses`, naming the binary and keeping the log; the profiler retry is
skipped because it cannot help. Updating the parser for a new format is part
of `contributing.md`.
## Writing the report
SKILL.md step 4 has the Summary / Notes template around the script's block.
Nothing in that block is typed by hand; each field comes from the device or
the run:
Report field | Comes from
------------------------------------------- | ----------
Device name, SoC, Android version | `ro.product.model`, `ro.soc.model`, `ro.build.version.release` on the attached phone (a Pixel 11 reports itself as Pixel 11 / Tensor G6)
Model name, size, compiled-for SoC | the `.tflite` file and its `LiteRtStamp`
**Compile** (flags, ops offloaded / total) | the `<model>.compile.json` sidecar next to the model; `unknown` when the model was compiled elsewhere - never fill it in from memory
**Versions** | the sidecar's `ai-edge-litert` version (the LiteRT that compiled the model) vs the bucket release in the binaries' URLs (`user-provided` for local files): `same release`, `DIFFERENT releases`, or why the two cannot be compared (no sidecar, a rolling `latest`/`nightly` build, local files, binaries from two sources); also stored as `versions` in `results.json`
**Delegation (runtime)** | the `Replacing N out of M node(s) with delegate (DispatchDelegate)` line of this run's `npu.log` - the ground truth that everything ran on the TPU
Mode, requested run counts, NPU flags | the flags actually passed to `benchmark_model`
**Thermal before NPU run** | `dumpsys thermalservice`: the throttling status (0 = none) is the signal; the sensor value is one reading, informational only
**TPU tile time** (header line + table row) | the tile-time pass: the hook's `Total TPU tile time` ÷ that pass's warmup + measured runs. The header names the hook's call count and what it means (`1 call per run, one per dispatch invoke`, or `2 calls per run (... the known double count, corrected)` with older dispatch libraries); `unavailable`, `failed`, `no report` or `inconsistent` (count matches no known pattern: totals only) carry the reason instead
**TPU energy** (header line + table row) | the same hooked pass: the power hook's `Total Energy` (the TPU rail from the first inference to the model's teardown, idle gaps included) ÷ that pass's warmup + measured runs, in mJ. The header names the hook's call count (`1 call per run, one per dispatch invoke`); `unavailable` (an old power hook, which the script does not enable, or a phone that refused the energy counter), `failed`, `no report`, `unreliable` (old hook's count pattern) or `inconsistent` carry the reason instead
Binary / dispatch library provenance | the resolver (`downloaded from <url>`, `cached download of <url>`, `user-provided: <path>`); downloads end with `(fetched <UTC time>, md5 <hash>)` recorded at download time, which identifies the build of a rolling release
All timings, memory, actual run counts | parsed from the `BENCHMARK RESULTS` block of this run's log
**Inference p5 / p50 / p95 (ms)** | the measured-phase `count=N ... p5= median= p95=` stats line of the log (microseconds, converted to ms by the script); these are the only percentiles `benchmark_model` produces - there is no p99
**Log check** | the script's scan of `npu.log` / `cpu.log` / `tile_time.log`: WARNING/ERROR-level lines that match the benign list above ("Log lines that are expected") are only counted (`N known-benign`); any other such line is listed verbatim under **Unexpected log lines** after the table (de-duplicated, with a repeat count), and the line also says whether the profiler retry happened. No grepping of the logs is needed.
Without a CPU baseline the Summary line is just `**Summary:** <NPU "Inference
avg"> ms per inference on the TPU (<strict NPU | CPU fallback allowed>, no CPU
comparison requested); peak memory <NPU> MB.` plus the same TPU tile time and
TPU energy sentences. Drop each of those two sentences when its header line says
`not measured`, `unavailable`, `failed`, `no report`, `unreliable` or
`inconsistent`, and give the header's reason in the Notes.
Combined compile + benchmark job: present only the benchmark block (its
**Compile** header line already carries the sidecar's flags and op counts)
and start the Notes with one line of compile context - that the input was
uncompiled and was compiled first, the output path, and that nothing existing
was overwritten (`compile_model.py` made sure of that). The SKILL.md step 2b
compile-only block is for jobs that end at the compile.
What to say in the Summary and Notes:
- Report the **actual** run counts from the table: `benchmark_model` treats
`--num_runs`/`--warmup_runs` as minimums and also runs for at least 1 s /
0.5 s, so fast models show more runs than requested ("Flags used" above;
the example output below is from a real run).
- The **Mode** line says whether the run was strict NPU or allowed CPU
fallback; call that out in prose as well, because fallback numbers mix NPU
and CPU time.
- The **Versions** line compares the LiteRT that compiled the model with the
release that ran it. Mention `DIFFERENT releases`, a
`but SDK package X (DIFFERENT)` or binaries from two sources in the Notes -
numbers from such a mix are harder to compare with other runs - unless the
line ends with `(the pair verified in versions.json)`.
`not comparable (...)` and `cannot compare` need no comment beyond the line.
- A speed-up below 1x is a real result, not a setup error, for tiny models
(per-inference NPU dispatch overhead of a few ms dominates); say so instead
of hunting for thermal or configuration problems.
- The per-op profile (`npu_profile.txt`) shows one `DELEGATE` node whose
average is lower than the table's `Inference avg` (it excludes input/output
handling); report the table value, not the profile value.
- **TPU tile time** is pure TPU hardware time, so it is below `Inference avg`
(which adds host and driver work). Quote it from the table only, never from
the hook's own lines in `tile_time.log` / `tile_time_report.txt`: older
dispatch libraries inflate its `Total inferences`, so their `Average` is too
low (half for a normal compiled model), while the table value is right with
every library.
- **TPU energy** is the TPU rail's energy (the phone's on-device power
monitor) for the whole hooked pass divided by its runs, so it includes the
TPU's idle gaps between back-to-back inferences: compare it between models,
builds and `--performance-mode`s on the same phone, and do not present it as
a lab power measurement or as the energy of one isolated inference. Quote it
from the table only.
## Example script output (one real run; never reuse these numbers)
Everything below was printed by `benchmark_on_device.py` for a Pixel 10 with
the public `selfie_multiclass_256x256` model compiled by `compile_model.py`
(so the `.compile.json` sidecar existed); each field is read from the device,
the sidecar or the run, so on a Pixel 11 the first line reads `Pixel 11 ...
SoC Tensor G6` without any change to the skill. Expect every number to differ
between runs (the same phone gave 14.10, 14.48, 15.13, 15.38, 16.10 and
16.25 ms avg in different runs). Without a sidecar the `Compile` line reads
`unknown - no <model>.compile.json next to the model (compiled elsewhere); see
Delegation below`.
**Example only** - values from one past run on one phone; they are never
reused. Your run prints its own.
```markdown
**Device:** Pixel 10 (serial localhost:41015), SoC Tensor G5, Android 17
**Model:** selfie_multiclass_256x256_Google_Tensor_G5.tflite (8,110,864 bytes (8.1 MB), compiled for Tensor_G5)
**Compile:** --target Tensor_G5; 175 / 175 ops offloaded (from selfie_multiclass_256x256_Google_Tensor_G5.tflite.compile.json)
**Versions:** compiled with ai-edge-litert 2.1.6; runtime binaries from bucket release '2.3.0' - DIFFERENT releases (the pair verified in versions.json)
**Delegation (runtime):** 1 of 1 node(s) replaced by DispatchDelegate at run time
**Mode:** strict NPU (--use_cpu=false --require_full_delegation=true); requested 5 warmup / 50 measured runs (actual counts in the table)
**Thermal before NPU run:** throttling status 0 (none); TPU sensor 45.0 C (single reading, informational)
**Benchmark binary:** downloaded from https://storage.googleapis.com/litert/binaries/2.3.0/android_arm64/benchmark_model (fetched 2026-10-07 07:22:39 UTC, md5 i+CfsHfR9Ao6uje4HUySvg==)
**Dispatch library:** downloaded from https://storage.googleapis.com/litert/binaries/2.3.0/android_arm64/libLiteRtDispatch_GoogleTensor.so (fetched 2026-10-07 07:22:37 UTC, md5 VuNepRvYbhpk4UjeRM2JvA==)
**NPU flags:** `--graph=/data/local/tmp/litert_benchmark/run-20261007-072235-139177/selfie_multiclass_256x256_Google_Tensor_G5.tflite --use_npu=true --use_cpu=false --require_full_delegation=true --dispatch_library_path=/data/local/tmp/litert_benchmark/run-20261007-072235-139177 --num_runs=50 --warmup_runs=5 --report_peak_memory_footprint=true --use_profiler=true`
**Log check:** npu.log: 0 unexpected WARNING/ERROR lines (1 known-benign); cpu.log: 0 unexpected WARNING/ERROR lines (0 known-benign); profiler retry: none
**Logs:** results/binaries_2.3.0
| Metric | NPU (Tensor_G5) | CPU baseline |
|---|---|---|
| Model file | selfie_multiclass_256x256_Google_Tensor_G5.tflite | selfie_multiclass_256x256.tflite |
| Model init (ms) | 254.38 | 57.33 |
| Warmup first (ms) | 13.13 | 138.93 |
| Warmup avg (ms) | 13.37 | 122.17 |
| Inference avg (ms) | 14.10 | 117.89 |
| Inference min / max (ms) | 8.09 / 31.03 | 115.49 / 118.67 |
| Inference std (ms) | 4.03 | 0.61 |
| Inference p5 / p50 / p95 (ms) | 8.621 / 14.017 / 19.585 | 116.654 / 118.072 / 118.462 |
| Peak memory (MB) | 124.99 | 205.75 |
| Runs (warmup / measured) | 37 / 70 | 5 / 50 |
NPU speed-up vs CPU (avg latency): **8.36x**
```
The percentile row comes from the measured-phase stats line that
`benchmark_model` logs in microseconds (`INFO: count=70 ... p5=8621
median=14017 p95=19585`), converted to ms by the script; p5 / median / p95 are
the only percentiles the tool produces (no p99). The row is omitted when the
log has no such line.
Two header lines in more detail:
* **Versions** (right after **Compile**):
`<compile part>; <runtime part> - <verdict>`. The compile part is
`compiled with ai-edge-litert <version from the sidecar's packages>` (plus
`but SDK package <v> (DIFFERENT)` when the sidecar's SDK package differs),
`compile version unknown (no compile sidecar)` or
`compile version not recorded in the sidecar`. The runtime part is
`runtime binaries from bucket release '<release>'` (from the URLs),
`... from user-provided files` / `... from a custom URL`, or both binaries
named separately when they differ. The verdict is `same release`,
`DIFFERENT releases` (with `(the pair verified in versions.json)` appended
when that is exactly the pinned pair), `not comparable (<reason>)` for a
rolling release (`latest`, `nightly`), local files or a URL without a
release, `cannot compare` without a sidecar version, or
`the two runtime binaries come from different sources`. In the example,
2.1.6 and 2.3.0 were the pinned pair at the time (why they differed: "Why
two release fields" in `contributing.md`), and this run is what verified
it.
* **Benchmark binary** / **Dispatch library** end with the fetch record:
`(fetched <UTC time>, md5 <base64 md5 from the bucket>)`, or
`sha256 <first 16 hex digits>` when the server sent no md5, or
`(fetch date not recorded; --refresh-binary re-downloads and records it)`
for files cached before the record existed. `downloaded from` marks the run
that fetched the file (as in the example); later runs say
`cached download of`.
The **Log check** line is the script's own scan of the logs (see "Log lines
that are expected" above): `1 known-benign` here is the plugin-path warning
that every AOT-compiled model triggers. When a log contains any other
WARNING/ERROR-level line, the count is non-zero and an **Unexpected log
lines** section follows the table, listing each distinct line verbatim (with
`(xN)` when it repeats, at most 8 shown), e.g. for a model compiled for the
wrong SoC and run with `--allow-mismatch`:
```text
**Unexpected log lines** (not in the benign list of references/benchmark-flags.md; judge them before reporting):
- npu.log: `ERROR: [litert_dispatch_invocation_context.cc:238] Failed to wait for SB invocation context`
- npu.log: `ERROR: Node number 1 (DELEGATE) failed to invoke. (x4301)`
```
`profiler retry: yes - ...` means the first, profiled NPU attempt failed and
the table comes from the retry without `--use_profiler` (first attempt's log:
`npu_profiled_attempt.log`).
When the NPU is slower than the CPU the last line adds `- the CPU was faster
by N.NNx (expected for tiny models: per-inference NPU dispatch overhead
dominates)`; a 568-byte single-`Add` model measured 2.85 ms on the TPU versus
0.08 ms on the CPU, which is overhead, not a configuration problem.
The same text is stored in `results.json` under `"markdown"`, next to the
structured fields (`device`, `thermal_before_npu_run`, `model`, `compile` (the
sidecar contents or `null`), `versions` (`compiled_with`, `runtime_release` of
`benchmark_model` and `dispatch_library`, the `pinned` pair from
`versions.json`, and `match`: `same`, `different`, `unverified`, `unknown` or
`mixed_runtime`), `npu` (including `delegated_nodes` / `total_nodes`), `cpu`,
`tpu_tile_time` (`status` (`ok`, `skipped`, `unavailable`, `failed`,
`no_report`, `inconsistent`), `reason`, `runs`, `warmup_runs`, `measured_runs`,
`dispatch_nodes`, `total_us`, `hook_count`, `count_ratio`, `count_meaning`,
`per_inference_ms`, `source` (`file` or `log`), `hook_registered`,
`pass_inference_avg_ms`, `flags`, `env`), `tpu_energy` (`status` (`ok`,
`skipped`, `unavailable`, `failed`, `no_report`, `unreliable`, `inconsistent`),
`reason`, `runs`, `warmup_runs`, `measured_runs`, `dispatch_nodes`, `total_uj`,
`hook_count`, `count_ratio`, `count_meaning`, `per_inference_mj`, `source`,
`hook_registered`, `flags`, `env`), `benchmark_binary`, `dispatch_library`,
`log_check` (per log: `benign_lines`, `unexpected_total`, `unexpected_lines`;
plus `retried_without_profiler`)), and written as `report.md` in the output
directory. In the printed block, paths under the current working directory are
shown relative to it (run from the project directory, the last line reads
`**Logs:** results/binaries_2.3.0`; paths elsewhere stay absolute);
`results.json` keeps the full paths.
Thermal line: the status (`0 (none)` ... `6 (shutdown)`, from
`dumpsys thermalservice`) is the meaningful part. The TPU sensor reading is
shown when the phone exposes one, but on the Pixel 10 used for these runs it
reported a constant `45.0 C` across hours and workloads, so do not read a
temperature trend into it.
### Example with TPU tile time and energy (real run; never reuse the numbers)
The example above was recorded before the TPU tile time and energy existed. A
current run adds the **TPU tile time** and **TPU energy** header lines and table
rows, and `tile_time.log` in the Log check. Verbatim `report.md` of a Pixel 10
run (2026-10-26, `2.3.1` binaries as re-uploaded on 2026-10-23, a 143 MB
`efficientnet_b7` compiled by `compile_model.py`, with a CPU baseline; this is
the run `verified.evidence` in `versions.json` names):
```markdown
**Device:** Pixel 10 (serial localhost:41015), SoC Tensor G5, Android 17
**Model:** efficientnet_b7_Google_Tensor_G5.tflite (142,963,424 bytes (143.0 MB), compiled for Tensor_G5)
**Compile:** --target Tensor_G5; 930 / 930 ops offloaded (from efficientnet_b7_Google_Tensor_G5.tflite.compile.json)
**Versions:** compiled with ai-edge-litert 2.1.6; runtime binaries from bucket release '2.3.1' - DIFFERENT releases (the pair verified in versions.json)
**Delegation (runtime):** 1 of 1 node(s) replaced by DispatchDelegate at run time
**Mode:** strict NPU (--use_cpu=false --require_full_delegation=true); requested 5 warmup / 50 measured runs (actual counts in the table)
**Thermal before NPU run:** throttling status 0 (none); TPU sensor 45.0 C (single reading, informational)
**TPU tile time:** from the dispatch library's hook (LITERT_VENDOR_HOOK_ARGS) in a separate hooked pass of 66 runs (16 warmup + 50 measured; warmups included): 1169.13 ms in total; the hook counted 66 = 1 call per run, one per dispatch invoke; per inference = total / 66 runs
**TPU energy:** from the dispatch library's power hook (LITERT_VENDOR_HOOK_ARGS) in the hooked pass of 66 runs (16 warmup + 50 measured; warmups included): 1404.45 mJ on the TPU rail from the first inference to the model's teardown, idle gaps included; the hook counted 66 = 1 call per run, one per dispatch invoke; per inference = total / 66 runs
**Benchmark binary:** cached download of https://storage.googleapis.com/litert/binaries/2.3.1/android_arm64/benchmark_model (fetched 2026-10-26 05:01:54 UTC, md5 bx6O455Ns4gjZWozKljNfQ==)
**Dispatch library:** cached download of https://storage.googleapis.com/litert/binaries/2.3.1/android_arm64/libLiteRtDispatch_GoogleTensor.so (fetched 2026-10-26 05:01:52 UTC, md5 tp26wryZhjaU3IYIz2w7/g==)
**NPU flags:** `--graph=/data/local/tmp/litert_benchmark/run-20261026-053057-3366899/efficientnet_b7_Google_Tensor_G5.tflite --use_npu=true --use_cpu=false --require_full_delegation=true --dispatch_library_path=/data/local/tmp/litert_benchmark/run-20261026-053057-3366899 --num_runs=50 --warmup_runs=5 --report_peak_memory_footprint=true --use_profiler=true`
**Log check:** npu.log: 0 unexpected WARNING/ERROR lines (2 known-benign); cpu.log: 0 unexpected WARNING/ERROR lines (0 known-benign); tile_time.log: 0 unexpected WARNING/ERROR lines (2 known-benign); profiler retry: none
**Logs:** bench_2.3.1_energy
| Metric | NPU (Tensor_G5) | CPU baseline |
|---|---|---|
| Model file | efficientnet_b7_Google_Tensor_G5.tflite | efficientnet_b7.tflite |
| Model init (ms) | 85.22 | 155.21 |
| Warmup first (ms) | 35.02 | 207.79 |
| Warmup avg (ms) | 25.06 | 202.04 |
| Inference avg (ms) | 26.33 | 200.05 |
| Inference min / max (ms) | 22.61 / 29.68 | 195.37 / 201.41 |
| Inference std (ms) | 1.98 | 0.96 |
| Inference p5 / p50 / p95 (ms) | 22.923 / 27.494 / 28.109 | 198.724 / 200.283 / 200.964 |
| TPU tile time / inference (ms) | 17.714 | - |
| TPU energy / inference (mJ) | 21.279 | - |
| Peak memory (MB) | 253.54 | 646.82 |
| Runs (warmup / measured) | 20 / 50 | 5 / 50 |
NPU speed-up vs CPU (avg latency): **7.60x**
```
The hooked pass ran 66 times and the NPU run 70 times (different warmup time
floors); the tile time and the energy use the hooked pass's own count. TPU tile
time (17.714 ms) is below `Inference avg` (26.33 ms) because it excludes host
and driver work. The hook counted one call per run, so its own
`Average TPU tile time (us): 17714.11` agrees with the table; on the `2.3.0`
binaries (2026-10-09) the same model gave 17.689 ms while the hook's own average
said 8844 us, half the real value. The TPU energy (21.279 mJ) is the power
report's `Total Energy (uJ): 1404446` divided by the 66 runs.
## Accuracy notes
* `benchmark_model` runs as a shell binary, which the LiteRT docs note is not
identical to in-app performance (different process priority, no app
sandbox). Use it for relative comparisons and regressions.
* Keep the phone unplugged from heavy workloads, screen on, and not thermally
throttled; repeat runs if `Inference (std)` is large relative to the mean.
compile-flags.md 15.1 KB
# Google Tensor compilation reference
Source of truth: the public LiteRT Python AOT API (`ai_edge_litert.aot`) and
https://developers.google.com/edge/tensor-sdk/compilation-flags. Everything in
`scripts/compile_model.py` maps 1:1 onto what is listed here.
## Contents
- [Python API used by the skill](#python-api-used-by-the-skill): Lines 16-50
- [Compiler flags (`google_tensor_*` kwargs)](#compiler-flags-google_tensor_-kwargs): Lines 52-68
- [Script options](#script-options): Lines 70-93
- [Package versions](#package-versions): Lines 95-131
- [Compiling on Google Colab (`--colab`)](#compiling-on-google-colab---colab): Lines 133-182
- [Interpreting the compilation report](#interpreting-the-compilation-report): Lines 184-191
## Python API used by the skill
```python
import os
os.environ["GOOGLE_TENSOR_BACKEND_ENABLED"] = "1" # before any LiteRT import
from ai_edge_litert.aot import aot_compile as aot_lib
from ai_edge_litert.aot.vendors.google_tensor import target as gt_target
target = gt_target.Target(gt_target.SocModel.TENSOR_G5) # or TENSOR_G6
result = aot_lib.aot_compile(
"/abs/path/model.tflite",
output_dir="/abs/path/work", # intermediates land here
target=target,
keep_going=False, # fail fast on backend errors
google_tensor_truncation_type="auto", # any google_tensor_* flag as kwarg
)
print(result.compilation_report()) # per-subgraph partition stats
result.export("/abs/path/out", model_name="model")
# -> /abs/path/out/model_Google_Tensor_G5.tflite
```
Facts worth remembering:
Item | Value
----------------------------------- | -----
`SocModel` enum values | `Tensor_G3`, `Tensor_G4`, `Tensor_G5`, `Tensor_G6`, `ALL` (case-sensitive strings)
Officially supported SoCs | `Tensor_G5` (Pixel 10 family), `Tensor_G6` (Pixel 11 family)
Backend id / target id | `GOOGLE` / `Google_Tensor_G5` (used as the export file suffix)
Default `output_dir` | API: `<input dir>/_compiled_models/` when omitted. `compile_model.py` instead writes to `--output-dir` (default `<model dir>/compiled/`) and refuses to overwrite an existing file unless `--overwrite` is given.
`keep_going` default | `True` (collects failures instead of raising) - the skill uses `False`
Env var for stable `ai-edge-litert` | `GOOGLE_TENSOR_BACKEND_ENABLED=1`, set **before** importing `ai_edge_litert.aot` (required by the public FAQ; the 2.1.6 Python wheel itself does not read it, so it is harmless and the script always sets it)
Compiler plugin location | Resolved from the `ai-edge-litert-sdk-google-tensor` package (`path_to_sdk_libs()`); fallback env var `GOOGLE_TENSOR_COMPILER_LIB`
Host | Local: Linux `x86_64` only; 16 GB RAM minimum (64 GB recommended for large inputs). Non-Linux hosts (`darwin`, `win32`, `linux/aarch64`) can compile remotely on a Google Colab Linux `x86_64` VM via `--colab` (`google-colab-cli`).
What the output records | The `LiteRtStamp` metadata holds the SoC only. The flags, the partition report (`ops_offloaded` / `ops_total`), the installed package versions (`packages`) next to the skill's pin (`pinned_pip_release`), and SHA-256 checksums of input, output and compiler library (`compiler_library_sha256`, which identifies the Beta tarball's compiler build) are written by `compile_model.py` to `<output>.compile.json` (plus `compiled_via: "colab"`, `colab_session`, and `local_host` when compiled with `--colab`); `check_compiled.py` and `benchmark_on_device.py` read that sidecar when it sits next to the model.
## Compiler flags (`google_tensor_*` kwargs)
| kwarg | CLI flag in `compile_model.py` | Values | Default | When to use |
|---|---|---|---|---|
| `google_tensor_truncation_type` | `--truncation-type` | `auto`, `bfloat16`, `half`, `no_truncation` | `auto` | Float precision on the TPU. `half` is the documented fix for compiler crashes on memory-constrained targets; it forces 16-bit floats, so the user must validate the outputs against the original model. |
| `google_tensor_sharding_intensity` | `--sharding-intensity` | `minimal`, `moderate`, `extensive`, `maximum` | `minimal` | How aggressively the graph is split. `maximum` pairs with `half` for crash recovery. |
| `google_tensor_int64_to_int32` | `--int64-to-int32` | bool | `False` | Models with int64 tensors the TPU cannot handle. |
| `google_tensor_enable_large_model_support` | `--large-model-support` | bool | `False` | Models larger than 2 GB. |
| `google_tensor_enable_4bit_compilation` | `--enable-4bit` | bool | `False` | Convolutions with 4-bit weights. |
| `google_tensor_extra_options_path` | `--extra-options-path` | path | `""` | Binary options file shipped with some pre-optimized models. |
The skill forwards only non-default values, so a plain
`compile_model.py model.tflite --target Tensor_G5` is identical to the
compiler's own defaults. Compilation is deterministic in practice: the same
input and flags produced byte-identical outputs (same SHA-256) in repeated
runs, which is how to tell whether an existing artifact matches a given flag
set when its sidecar is missing.
## Script options
`compile_model.py` sets `GOOGLE_TENSOR_BACKEND_ENABLED=1` (required by the
stable package), checks the installed LiteRT package versions against each
other and `versions.json`, calls `aot_compile(...,
target=Target(SocModel.TENSOR_G5), keep_going=False, google_tensor_*=...)`,
prints the compilation report, exports to `--output-dir`, re-verifies the
Tensor stamp and writes `<output>.compile.json` (flags, `ops offloaded /
total`, package versions, SHA-256 of input/output/compiler lib, elapsed time,
plus `compiled_via: "colab"` with `--colab`). Besides the compiler flags above
and the Colab flags below, it takes:
Flag | Purpose
-------------------- | -------
`--output-dir DIR` | Where to write the compiled model (default `<model dir>/compiled`).
`--output-name NAME` | Output file name (default `<model stem>_Google_<target>.tflite`).
`--overwrite` | Replace an existing output file (default: refuse with exit 2, so a previous artifact is never clobbered).
`--keep-going` | Continue past backend errors instead of failing fast (`keep_going=True`).
`--keep-intermediates` | Keep the compiler's intermediate files under `<output-dir>/_intermediates`.
`--no-report-file` | Do not write the `<output>.compile.json` sidecar.
`--json` | Print a JSON summary as the last line of stdout.
`--dry-run` | Validate inputs and print the plan; do not compile.
`--print-install` | Print the install commands for the pinned LiteRT pair (with `--colab`: the `google-colab-cli` setup), then exit.
`--force` | Experimental: skip the already-compiled check. The compiler cannot recompile `DISPATCH_OP` partitions, so this normally fails; compile the original export instead.
## Package versions
Pin LiteRT and the Google Tensor SDK package to the **same** version. The
skill's pin lives only in `versions.json` (`pip_release`, with the supported
`python` range and what it was last verified on); no script or instruction
repeats it, and a version number elsewhere in these references only labels
an observation made on that release. The public compatibility matrix lives at
https://developers.google.com/edge/tensor-sdk/release-notes#compatibility.
| Track | Install command |
|---|---|
| Stable (skill default) | printed by `python3 scripts/compile_model.py --print-install`: venv, then `export GOOGLE_TENSOR_SDK_BETA=/abs/path/litert_plugin_compiler.tar.gz` and `pip install --no-cache-dir ai-edge-litert==<pinned> ai-edge-litert-sdk-google-tensor==<pinned>` |
| Nightly | same, with `--pre ai-edge-litert-nightly ai-edge-litert-sdk-google-tensor-nightly` |
Before compiling, `compile_model.py` reads the installed versions
(`importlib.metadata`): `WARNING` on stderr when a runtime package and its SDK
package differ (stable or nightly pair), `NOTE` on stdout when the stable
pair matches itself but not the pin (allowed - the compile uses what is
installed). Both messages carry the reinstall line for the pinned pair. The
sidecar records `packages` (installed) and `pinned_pip_release`, so a report
never depends on which version someone believes was installed.
How the SDK package install works (verified against the published 2.1.6 sdist):
| Fact | Detail |
|---|---|
| Source distribution only | `ai-edge-litert-sdk-google-tensor` is an sdist; its `setup.py` runs a custom `build_py` that unpacks the compiler into `ai_edge_litert_sdk_google_tensor/data/`. |
| `GOOGLE_TENSOR_SDK_BETA` | **Required.** Absolute path to the Beta tarball (`.tar.gz`/`.zip`) from the sign-up e-mail. Missing -> `SDK location is not set. Aborting installation.`; wrong path -> `Google Tensor SDK beta file not found`. |
| `GOOGLE_TENSOR_ML_SDK_URL` | Alternative: a URL to download the tarball from (only used when `GOOGLE_TENSOR_SDK_BETA` is unset). |
| `SKIP_SDK_DOWNLOAD` | Installs the package without any compiler - only useful for testing; `compile_model.py` then exits 5. |
| Host gating | The unpack step only runs on Linux x86_64; elsewhere the package installs empty and `compile_model.py` exits 4. |
| What the wheel provides | `ai_edge_litert` ships the plugin adapter `libLiteRtCompilerPlugin_google_tensor.so`; it dlopens `liblitert_plugin_compiler.so` from the SDK `data/` directory (or `GOOGLE_TENSOR_COMPILER_LIB` when the SDK package is absent). |
| pip wheel cache | pip caches the SDK wheel it built; after a failed/empty first attempt re-install with `--no-cache-dir --force-reinstall`. |
| Python versions | Supported range: `python` in `versions.json` (printed by `--print-install`, which also warns when the current Python is outside it). Observed for 2.1.6: manylinux x86_64 wheels (cp313 verified: `cp313-manylinux_2_27_x86_64`). |
When a new release is adopted, re-check the rows above against its sdist
(`references/contributing.md` lists what to re-verify).
## Compiling on Google Colab (`--colab`)
When the user's machine is not Linux `x86_64` (e.g. macOS, Windows, or Linux
ARM) or they prefer not to install the compiler locally, `compile_model.py
--colab` runs the exact same compilation on a remote Google Colab Linux `x86_64`
VM using `google-colab-cli` (`https://github.com/googlecolab/google-colab-cli`),
while keeping the input/output `.tflite` and `<output>.compile.json` sidecar on
the local machine for `check_compiled.py` and `benchmark_on_device.py`.
If the user prefers an interactive browser notebook instead of the CLI, point
them to the official public Colab notebook:
https://github.com/google-ai-edge/litert-samples/blob/main/samples/litert/colab/LiteRT_AOT_Compilation_Tutorial.ipynb
CLI flag in `compile_model.py` | Default | Purpose
------------------------------ | ------------------------------------------------------ | -------
`--colab` | `False` | Run the compile step on a remote Google Colab Linux `x86_64` VM via `google-colab-cli` (`colab`).
`--sdk-tarball FILE` | `$GOOGLE_TENSOR_SDK_BETA` | Local path to `litert_plugin_compiler.tar.gz` (from the Google Tensor SDK Beta e-mail) to upload to the Colab VM when installing `ai-edge-litert-sdk-google-tensor`.
`--sdk-url URL` | `$GOOGLE_TENSOR_ML_SDK_URL` | Alternative to `--sdk-tarball`: download URL for the Beta tarball fetched directly by the Colab VM.
`--colab-session NAME` | `litert-gt-<pid>` | Session name for `colab`. If `NAME` is already listed in `colab sessions`, the script reuses that VM instead of calling `colab new` and leaves it running at the end; otherwise it creates `NAME` and stops it when done (unless `--keep-colab-session` is set).
`--keep-colab-session` | `False` | Keep a newly created Colab VM running after the compile so a subsequent `--colab-session NAME` run skips uploading the tarball and `pip install`.
`--colab-high-mem` | `False` | Pass `--high-mem` to `colab new` when creating a new Colab VM (useful for large models or when a standard VM runs out of memory).
`--colab-timeout SECS` | `900` | Timeout in seconds for the remote Colab compile execution (`colab exec --timeout`).
`--colab-auth {oauth2,adc}` | `colab` default (`oauth2`) | Authentication mode passed before the `colab` subcommand (`colab --auth <mode> <subcommand> ...`).
`--colab-auth-code CODE` | `None` | Exchanges a one-time OAuth authorization code (from the URL printed by a previous `--colab` run) and saves `~/.config/colab-cli/token.json` so the user never has to run a terminal command.
`--colab-bin PATH` | `$LITERT_GOOGLE_TENSOR_COLAB_BIN` or `colab` on `PATH` | Path to the `google-colab-cli` executable (also checks `~/.venvs/colab-cli/bin/colab` and `~/.local/bin/colab`).
How `compile_model.py --colab` works:
1. **Local pre-flight before allocating a VM:** validates the input `.tflite`
(refuses an already-compiled model with exit 3), checks output collision
(exit 2 unless `--overwrite`), locates `colab` on `PATH`, and verifies that
`--sdk-tarball` or `--sdk-url` is available before calling `colab new`.
2. **Session check & probe:** runs `colab sessions` (read-only API call) to
verify authentication and check if `--colab-session` is already active. On a
reused session, probes whether `ai-edge-litert` and
`ai-edge-litert-sdk-google-tensor` (at `versions.json`'s `pip_release`) and
`liblitert_plugin_compiler.so` are already present; if so, skips uploading
the Beta tarball and skips `pip install`.
3. **Remote install & subprocess compile:** checks `ctypes.CDLL("libc++.so.1")`
on the Colab VM (installing `libc++1 libc++abi1` via `apt-get` if missing,
matching the public Colab tutorial), runs `pip install --no-cache-dir` with
`GOOGLE_TENSOR_SDK_BETA` set, and invokes the uploaded `compile_model.py` in
a **fresh child Python subprocess** (so newly installed C extensions and
shared libraries load cleanly without needing `colab restart-kernel`).
4. **Download & verification:** downloads `<output>.tflite` and
`<output>.compile.json`, verifies the `LiteRtStamp` and `output_sha256`,
stamps `"compiled_via": "colab"`, `"colab_session"`, and `"local_host"` into
the sidecar, and stops the Colab VM in a `finally:` block (including on
Ctrl-C / `SIGINT` / `SIGTERM`) whenever the script created the session and
`--keep-colab-session` was not set.
## Interpreting the compilation report
`compilation_report()` prints, per backend, the partition statistics: how many
subgraphs/ops were offloaded to the TPU and which ops stayed on the CPU. A
model is only useful for the strict NPU benchmark (`--require_full_delegation`)
when **all** ops were offloaded; otherwise either fix the model (static shapes,
supported ops) or run `benchmark_on_device.py --allow-cpu-fallback`, accepting
that the reported latency then mixes NPU and CPU time.
contributing.md 18.4 KB
# Contributing to litert-google-tensor
Read this before changing the skill, and follow the runbook below whenever a
new LiteRT release is adopted. Agents running a user job never need this
file.
## Contents
- [Invariants (DO NOT BREAK)](#invariants-do-not-break): Lines 17-95
- [`versions.json`](#versionsjson): Lines 97-130
- [Why two release fields](#why-two-release-fields): Lines 110-130
- [Adopting a new LiteRT release](#adopting-a-new-litert-release): Lines 132-226
- [Updating the benchmark output parser](#updating-the-benchmark-output-parser): Lines 228-248
- [Editing Principles](#editing-principles): Lines 250-265
- [Validation](#validation): Lines 267-293
## Invariants (DO NOT BREAK)
- **`versions.json` is the only place a LiteRT version is pinned.**
`compile_model.py` reads `pip_release` and `python`; `benchmark_on_device.py`
reads `binaries_release` (default download URLs) and `pip_release` (the
report's Versions line); `package_ai_pack.py` reads `maven_release` (the
Gradle coordinates it writes), `kotlin_min` (INTEGRATION.md) and
`pip_release` (its install hint); `install_and_verify.py` reads
`bundletool_release` (its default bundletool download).
`SKILL.md` and `references/` never repeat a pinned value as an
instruction; they say `<pinned>` or point to `compile_model.py
--print-install`. A version number anywhere else labels an observation
("observed with 2.1.6", "bucket listing checked 2026-10-07") and keeps the
version or date it was observed on.
- **One version for the runtime and SDK packages.** The pip line always pins
`ai-edge-litert` and `ai-edge-litert-sdk-google-tensor` to the same
`pip_release`; the compile-time WARNING exists because a mixed pair is not
supported.
- **`benchmark_model` and `libLiteRtDispatch_GoogleTensor.so` come from one
bucket release directory by default** (the dispatch URL is derived from the
benchmark URL). `binaries_release` must name a directory that ships both.
- **Scripts are standard-library Python 3 and stand alone.** Each script reads
`versions.json` itself (no shared helper module), so `--help`, `--dry-run`
and `--print-install` keep working with any `python3`, without LiteRT, and
with a missing or broken `versions.json`. Only the default download and the
installed-vs-pinned comparison may then fail, and their messages must name
the file.
- **All scripts classify models the same way.** Each one checks the bytes
itself: LiteRT build = `DISPATCH_OP` + `LiteRtStamp` (+ the SoC), other
toolchain = an `edgetpu-custom-op` custom op without them, plain =
neither. Change a marker in `check_compiled.py`, `compile_model.py`,
`benchmark_on_device.py` and `package_ai_pack.py` together.
- **Sidecar and results keys are an interface.** `check_compiled.py` reads
`cli_flags`, `ops_offloaded` and `ops_total` from `<model>.compile.json`,
`benchmark_on_device.py` reads those plus `packages` (Versions line) and
copies the whole sidecar into `results.json`; `package_ai_pack.py` checks
`output_sha256`, `target` and `input_sha256` and copies `cli_flags`,
`ops_offloaded`, `ops_total`, `fully_compiled`, `packages`, `compiled_at`
and `compiled_via` into `pack.json`; rename a key only together with every
reader. Keep the `results.json` keys documented in
`benchmark-flags.md`.
- **Report values come from script output only.** The example output in
`benchmark-flags.md` is verbatim from one real run: never edit its numbers
or lines. To refresh it, replace the whole block with a new run's
`report.md` and update `verified.evidence` in `versions.json`.
- **The packager leaves the AI-pack layout to LiteRT.** `package_ai_pack.py`
builds `export_lib.export()`'s input from the files on disk and never writes
pack folders or the device-targeting XML itself. Its only change to the
exporter's output is the `model#group_other` placeholder. When the
exporter's API or output changes, the script must fail (exit 5 or 7) and
this file must be updated; never add a hand-written fallback layout.
- **Update mode only reads the user's project.** `--update-project` writes
nothing there: it copies the exporter's output files to the app's existing
paths under `<output-dir>/files/` and describes every other change in
`UPDATE.md`. It matches device groups by the SoC in the app's XML (never
renames them), takes the group element for a new SoC from the exporter's
XML, and keeps the app's pack name, folder and file names.
- **Only the agent changes the user's project, and only after approval.**
`--check-project` and `--update-project` only read it. SKILL.md step 6
has the agent apply the plan after one approval, with a separate OK for
each item the check marks `risky`; keep `risky` on every fix that changes
more than the integration itself (build tool versions, adding Kotlin,
`minSdk`, the app's ABIs, the app's LiteRT release, replacing the user's
own files).
`install_and_verify.py` uninstalls only with `--uninstall-first`, and
nothing in the skill signs for release, publishes or uploads.
- **Templates follow LiteRT's published module layout.** `assets/templates/`
mirrors the `google_tensor_runtime` and `runtime_strings` modules of the
LiteRT NPU guide (https://developers.google.com/edge/litert/next/npu), with
one deliberate difference: the runtime module is delivered to exactly the
pack's device groups. Placeholders are `{{NAME}}`; the script fails on any
unfilled one.
- **Everything the skill ships is public.** Scripts, templates and docs use
only public endpoints and tools (PyPI, Google Maven, the public binaries
bucket, Gradle, bundletool): no company-internal paths, links or services.
- **No leftover processes, device files, or Colab sessions.** Tests and runs
must not leave adb or `benchmark_model` running, must not touch a phone
unless the change needs one, and must stop any Colab VM session created by
`compile_model.py --colab` unless `--keep-colab-session` was requested.
## `versions.json`
| Field | Read by | Format and meaning |
|---|---|---|
| `pip_release` | `compile_model.py` (`--print-install`, exit-5 install hints, WARNING/NOTE, sidecar `pinned_pip_release`); `benchmark_on_device.py` (Versions line) | PyPI version string `X.Y.Z` (validated against `\d[0-9A-Za-z.+!_-]*`) of both pip packages. |
| `binaries_release` | `benchmark_on_device.py` (default `--benchmark-url`, hence also the dispatch URL; Versions line) | A directory name under `https://storage.googleapis.com/litert/binaries/` (`latest`, `nightly` or `X.Y.Z`; validated against `[A-Za-z0-9._-]+`). |
| `maven_release` | `package_ai_pack.py` (Gradle files, INTEGRATION.md, `pack.json`) | Google Maven version that exists for both `com.google.ai.edge.litert:litert` and `com.google.ai.edge.litert:litert-npu-runtime-google-tensor` (validated against `\d[0-9A-Za-z.+_-]*`). Check: `https://dl.google.com/dl/android/maven2/com/google/ai/edge/litert/group-index.xml`. |
| `kotlin_min` | `package_ai_pack.py` (INTEGRATION.md requirements, `pack.json`) | `MAJOR.MINOR`: the oldest Kotlin that can read the Kotlin metadata of `litert-api` at `maven_release`. A Kotlin compiler reads metadata up to one minor version newer than itself, so metadata 2.4.0 needs Kotlin 2.3. Check: `javap -v` on any class of the AAR's `classes.jar` shows `mv` (the metadata version); confirm by building an app with the package applied (step 6a) on exactly that Kotlin. |
| `bundletool_release` | `scripts/install_and_verify.py` (default download of `bundletool-all-<v>.jar`) | A bundletool release that exists on GitHub with a `bundletool-all-<v>.jar` asset (https://github.com/google/bundletool/releases); 1.18.0 or newer (local testing of AI packs). |
| `python` | `compile_model.py --print-install` | `MAJOR.MINOR-MAJOR.MINOR`: the interpreters with published wheels for `pip_release`. |
| `verified` | printed by `--print-install` as `Last verified: ...` | Free-form strings: `date`, `evidence` (which run proves the pair works), `device`, `host`, `binaries` (the bucket build, ideally with the md5 from the provenance line), and `app` (the latest end-to-end app check on a Pixel: date, device, delivery modes, `maven_release`, bundletool and build tool versions). |
| `_comment` | people | Ignored by the scripts. |
### Why two release fields
The bucket and the pip index are separate sources, and one field could not
serve both:
- Numbered bucket directories before 2.3.0 ship no Google Tensor dispatch
library (bucket table in `benchmark-flags.md`), so earlier pins took the
binaries from `latest`.
- The pip index users install from can lag the bucket. Many organizations
install through a pip mirror or proxy that holds newly published
third-party releases back for a while: on 2026-10-07 the bucket and PyPI
had 2.3.0, while such a mirror offered only 2.2.0 and older.
- The Tensor SDK compatibility matrix names the stable `ai-edge-litert`
release to compile with
(https://developers.google.com/edge/tensor-sdk/release-notes#compatibility),
and it can be older than the newest bucket release.
A split pin is fine once verified; the report then says `DIFFERENT releases
(the pair verified in versions.json)`. With both fields on one numbered
release it says `same release`; with a rolling `latest` it can only say
`not comparable`. Close the gap when the index catches up (runbook below).
## Adopting a new LiteRT release
Not every release needs adopting. Do it when a release fixes something users
hit, adds a SoC, or the Tensor SDK release notes require it, or periodically.
Until then the skill keeps working on the old pin; pinning exists for exactly
that.
Where releases show up: `https://pypi.org/project/ai-edge-litert/#history`,
the bucket's release directories
(`https://storage.googleapis.com/storage/v1/b/litert/o?prefix=binaries/&delimiter=/&fields=prefixes`),
and the compatibility matrix in
https://developers.google.com/edge/tensor-sdk/release-notes#compatibility.
You need a Linux x86_64 host, the Beta tarball, a Pixel 10 (and a Pixel 11 if
available) and a model with a known-good earlier result (e.g. the public
`selfie_multiclass_256x256` of the example in `benchmark-flags.md`).
1. **Check what exists (no install).**
- PyPI has `ai-edge-litert` and `ai-edge-litert-sdk-google-tensor` at the
same version `V` (`https://pypi.org/pypi/<package>/V/json` answers).
- The pip index users install from offers both at `V`
(`python3 -m pip index versions <package>`). A pip mirror or proxy
(configured in `pip.conf` or `PIP_INDEX_URL`) can lag PyPI. If either
package is missing there, leave `pip_release` as it is and move only
`binaries_release`.
- `https://storage.googleapis.com/storage/v1/b/litert/o?prefix=binaries/V/android_arm64/&fields=items(name,size,md5Hash,updated)`
lists both `benchmark_model` and `libLiteRtDispatch_GoogleTensor.so`. If
the dispatch library is missing, leave `binaries_release` as it is and
move only `pip_release`.
- Compare that listing's `md5Hash` of the dispatch library with the pinned
build's (`verified.binaries`): the same md5 means nothing changed on the
Google Tensor side, whatever the release notes say (the first `2.3.1`
upload of 2026-10-20 carried `2.3.0`'s library byte for byte). Release
directories can be re-uploaded (`2.3.1` was, on 2026-10-23), so note
both md5s and expect them in step 5's provenance lines.
- Google Maven lists `litert` and `litert-npu-runtime-google-tensor` at
`V` (group index above). If not, leave `maven_release` as it is.
- When `maven_release` moves: read the Kotlin metadata version of the new
`litert-api` (`javap -v`, field `mv`) and update `kotlin_min`.
- The release notes say whether the existing Beta tarball still applies.
2. **Edit `versions.json`**: `pip_release` and `binaries_release` as far as
step 1 allows, `python` if the wheel matrix changed. Leave `verified` for
step 6.
3. **Install into a fresh venv** (skip if `pip_release` did not change). Run
`python3 scripts/compile_model.py --print-install` and run the printed
commands with `GOOGLE_TENSOR_SDK_BETA` set, changing only the venv path
(e.g. `~/.venvs/litert-tensor-V`) so the working venv stays intact. The
SDK package's `data/` directory must contain `liblitert_plugin_compiler.so`.
If the install rejects the tarball, the tarball is tied to an SDK version:
stop and revert, or get the matching tarball first.
4. **Compile** with the new venv (or the existing one if step 3 was skipped):
`<venv>/bin/python scripts/compile_model.py <model> --target Tensor_G5
--output-dir <dir>`. Expect exit 0 with no WARNING or NOTE, the sidecar's
`packages` at `pip_release`, `fully_compiled: true`, and op counts like the
previous release's (a different `output_sha256` across compiler releases is
normal; note it).
5. **Benchmark on the phone**: `python3 scripts/benchmark_on_device.py --model
<compiled> --cpu-baseline <original> --refresh-binary --output-dir <dir>`.
Expect exit 0, every table row filled, the Versions line as intended
(`same release` when both fields name one release, otherwise
`DIFFERENT releases (the pair verified in versions.json)`), and
`0 unexpected` in the Log check. New benign log lines go into
`_BENIGN_LOG_LINES` and the benign table in `benchmark-flags.md`; exit 6
"printed no results in the format this script parses" means the parser needs
updating (next section). Check the TPU telemetry too: the **TPU tile time**
line must name a known call pattern
(`1 call per run, one per dispatch invoke` with the `2.3.1` binaries
re-uploaded on 2026-10-23, observed 2026-10-26; `2 calls per run` with
`2.3.0`, 2026-10-09). The formula needs no change for either; a new pattern
needs a row in the table under "TPU tile time" in `benchmark-flags.md`. The
**TPU energy** line must say `1 call per run, one per dispatch invoke` too
(`2.3.1` re-upload, 2026-10-26), or name why not. The provenance lines must
show the md5s noted in step 1.
6. **Record the evidence** in `versions.json` `verified`: date, the run's
output directory or run id, device, host, and the binaries build (release
and md5 from the provenance lines). To make this run the documented
example, replace the example block in `benchmark-flags.md` with its
`report.md`, unchanged.
7. **Re-verify the version-labelled observations** and add new ones labelled
with `V`:
- `compile-flags.md`: the "How the SDK package install works" table (sdist
behaviour, error strings, `SKIP_SDK_DOWNLOAD`, host gating), the Python
wheels row, the `GOOGLE_TENSOR_BACKEND_ENABLED` note.
- `troubleshooting.md`: rows that name a version.
- `benchmark-flags.md`: the bucket table (re-check the listing and update
its "checked" date), the output format block, the benign log lines, the
interoperability note.
8. **Packaging** (when `pip_release` or `maven_release` changed): diff the
new release's `ai_edge_litert/aot/ai_pack/export_lib.py` against the old
one, then package a build and run steps 6 and 7 on a Pixel 10 (and a
Pixel 11 if available).
9. Run the checks under "Validation" and send the change for review with the
evidence from steps 4-6 and 8.
If a step fails, revert `versions.json`; nothing else depends on the attempt.
## Updating the benchmark output parser
When a `benchmark_model` build exits 0 but `benchmark_on_device.py` stops with
exit 6 "printed no results in the format this script parses":
1. Take `npu.log` from the run's output directory.
2. Extend `_PATTERNS` (and, if needed, `_DELEGATION_RE`, `_PHASE_STATS`,
`_LEGACY_TIMINGS`, `_LEGACY_PEAK`) in `benchmark_on_device.py`. Keep the
existing patterns working: older builds stay in users' caches.
3. Replace the block under "Output format parsed by the script" in
`benchmark-flags.md` with the new results block, verbatim.
4. Re-run and check that every table row is filled.
The dispatch library's hook reports are parsed the same way: `_TILE_TOTAL_RE` /
`_TILE_COUNT_RE` (tile time) and `_POWER_TOTAL_RE` / `_POWER_COUNT_RE` (energy).
If a library changes their format, the header says `no report`: extend the
patterns and replace the report blocks under "TPU tile time" and "TPU energy" in
`benchmark-flags.md`. `_POWER_OLD_MARKER` (a log string only the old power hook
has) keeps the power metric off for old libraries; drop it once no supported
library carries the old hook (the Maven runtime AAR did up to 2.3.0, and apps
built with it keep shipping it; the 2.3.2 AAR does not, checked 2026-10-27).
## Editing Principles
- `SKILL.md` holds the workflow an agent follows during a user job;
`references/` hold tables and details it loads on demand. A fact lives in
one place, and the other links to it.
- Keep the `SKILL.md` body under 500 lines, link every file under
`references/`, `scripts/` and `assets/` from `SKILL.md` with a relative
Markdown link, and keep the table of contents at the top of each reference
over 100 lines in sync (anchor links and line hints) when you edit it.
- Instructions name no version; observations always name the version or
date they were made on.
- Every script error names its fix, and exit codes match the scripts'
docstrings, `SKILL.md` and the references. A new failure mode gets a
`troubleshooting.md` row.
- Python style: 2-space indentation, 80 columns for new lines, standard
library only.
## Validation
Run from the skill directory; none of these needs a phone, the network or
LiteRT:
```bash
python3 -m py_compile scripts/*.py
python3 -c "import json; json.load(open('assets/versions.json'))"
python3 scripts/compile_model.py --print-install
python3 scripts/compile_model.py --print-install --colab
python3 scripts/compile_model.py --help
python3 scripts/check_compiled.py --help
python3 scripts/benchmark_on_device.py --help
python3 scripts/benchmark_on_device.py --model <any compiled .tflite> --dry-run
python3 scripts/package_ai_pack.py --help
python3 scripts/install_and_verify.py --help
```
`--print-install` must show the new pin, and `--dry-run` the default URLs for
`binaries_release` (it needs an `adb` on PATH but does not run it). Search the
docs for leftover numbers: in `SKILL.md` and `references/`, `==` must be
followed by `<pinned>` and `binaries/` by `<release>`, a non-numeric
directory such as `latest`, or a labelled observation. Changes to the compile
or benchmark paths also need steps 3-5 of the runbook on real hardware.
Links in the skill must be public: no URLs that need a company network,
VPN or login, and no short links that only resolve inside one organization.
troubleshooting.md 47.8 KB
# Troubleshooting
Symptoms are grouped by phase. Public references:
FAQ https://developers.google.com/edge/tensor-sdk/tensor-faqs,
NPU guide https://developers.google.com/edge/litert/next/npu,
issues https://github.com/google-ai-edge/LiteRT/issues.
## Contents
- [Environment and install](#environment-and-install): Lines 19-38
- [Compilation](#compilation): Lines 40-54
- [adb and device](#adb-and-device): Lines 56-68
- [Host-side binaries (benchmark_model, dispatch library)](#host-side-binaries-benchmark_model-dispatch-library): Lines 70-79
- [benchmark_model on the device](#benchmark_model-on-the-device): Lines 81-107
- [Packaging for an app (`package_ai_pack.py`, the app build)](#packaging-for-an-app-package_ai_packpy-the-app-build): Lines 109-168
- [Updating an app (`--update-project`)](#updating-an-app---update-project): Lines 133-146
- [Applying the plan (`--check-project`) and checking on a Pixel (`install_and_verify.py`)](#applying-the-plan---check-project-and-checking-on-a-pixel-install_and_verifypy): Lines 148-168
## Environment and install
Symptom | Cause | Fix
----------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---
`python3 -m venv ...` fails: `ensurepip is not available` | Debian/Ubuntu ship the venv module separately | `sudo apt install python3-venv` (or `python3.X-venv` for a specific minor version), then rerun the `venv` command.
`ModuleNotFoundError: ai_edge_litert.aot` or `cannot import ... google_tensor` | LiteRT not installed in the active interpreter, or an old `ai-edge-litert` without the AOT API | Activate the venv; install as in SKILL.md step 2a.
`compile_model.py` exit 5 `cannot import the LiteRT AOT API` although the venv install succeeded | The script was started with a different interpreter (system `python3`, a tool's bundled Python) than the one the packages were installed into | Run it with the venv's interpreter explicitly: `~/.venvs/litert-tensor/bin/python scripts/compile_model.py ...` (the venv `--print-install` creates; no activation needed).
`pip install` fails: `SDK location is not set. Aborting installation.` | `GOOGLE_TENSOR_SDK_BETA` was not exported; the SDK package has no built-in download URL (observed with 2.1.6) | `export GOOGLE_TENSOR_SDK_BETA=/abs/path/litert_plugin_compiler.tar.gz` (Beta e-mail), then re-run the `pip install` line printed by `compile_model.py --print-install`.
`pip install` fails: `Google Tensor SDK beta file not found` | Wrong tarball path | Fix the path (must be an existing `.tar.gz`/`.zip` file).
`compile_model.py` exit 4 / `NotImplementedError: ... only supported on Linux x86 architecture` | Compiler plugin is Linux `x86_64` only | Re-run with `--colab --sdk-tarball /abs/path/litert_plugin_compiler.tar.gz` (uses `google-colab-cli` to compile on a remote Google Colab Linux `x86_64` VM), or compile on a Linux `x86_64` box; benchmark from any OS with `adb`.
`compile_model.py --colab` exit 5: `'colab' CLI not found` | `google-colab-cli` is not installed or not on `PATH` | Run `python3 scripts/compile_model.py --print-install --colab` for the install commands (`uv tool install`, `pipx install`, or a venv), or pass `--colab-bin /abs/path/to/colab` (or env `LITERT_GOOGLE_TENSOR_COLAB_BIN`).
`compile_model.py --colab` exit 5: `failed to query Google Colab sessions` / OAuth or ADC error | `google-colab-cli` is not authenticated yet, or `--colab-auth adc` lacks the Drive + Collaboratory scopes | Run `colab sessions` once in an interactive terminal to complete browser OAuth (cached in `~/.config/colab-cli/`), or if using `--colab-auth adc`, run `gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/drive,https://www.googleapis.com/auth/colaboratory"`.
`compile_model.py --colab` exit 5: `--colab requires the Google Tensor SDK Beta tarball` (before `colab new`) | Neither `--sdk-tarball` (`GOOGLE_TENSOR_SDK_BETA`) nor `--sdk-url` (`GOOGLE_TENSOR_ML_SDK_URL`) was supplied and the target session does not already have the SDK installed | Pass `--sdk-tarball /abs/path/litert_plugin_compiler.tar.gz` (from the Google Tensor SDK Beta e-mail) or `--sdk-url <url>`. The script checks this before calling `colab new` so no Colab VM is allocated without it.
`compile_model.py` exit 5: `liblitert_plugin_compiler.so not found` / `Warning: SDK files directory not found at .../ai_edge_litert_sdk_google_tensor/data` | The SDK package was built without the Beta tarball (`SKIP_SDK_DOWNLOAD` set, or pip reused a cached wheel from an earlier attempt) | Reinstall with the variable set: the `pip install` line from `compile_model.py --print-install` plus `--force-reinstall`.
Compile fails, log shows `Failed to load Tensor TPU compiler library: liblitert_plugin_compiler.so: cannot open shared object file` | Same root cause as above, caught at run time | Same fix; `compile_model.py` maps this to exit 5 and prints the log lines.
`compile_model.py` prints `WARNING: ai-edge-litert X and ai-edge-litert-sdk-google-tensor Y differ` (or the same for the `-nightly` pair) | The runtime and SDK packages were installed at different versions, e.g. one was upgraded on its own | Reinstall both at one version with `GOOGLE_TENSOR_SDK_BETA` set: the reinstall line in the warning (pinned version, `--force-reinstall`). Compile results from a mixed pair are not a supported combination.
`compile_model.py` prints `NOTE: installed ...; versions.json pins V` | The venv holds a matching pair at a version other than the skill's pin (or only the nightly pair) | Allowed: the compile uses what is installed and the sidecar records it. For the pinned pair run the reinstall line from the note. If another version should become the pin, follow `contributing.md`.
No Google Tensor backend / "unsupported target" although the SDK is installed | `GOOGLE_TENSOR_BACKEND_ENABLED` missing with the stable package | The script sets it; if you call the API yourself, `export GOOGLE_TENSOR_BACKEND_ENABLED=1` before importing `ai_edge_litert`.
`libc++.so.1: cannot open shared object file` while importing/compiling | Host lacks libc++ (the public Colab installs `libc++-18-dev libc++abi-18-dev`) | `sudo apt-get install libc++-18-dev libc++abi-18-dev` (or your distro's libc++), then retry.
pip cannot find a matching `ai-edge-litert==<pinned>` wheel | Interpreter version without a published manylinux wheel (supported range: `python` in `versions.json`; for 2.1.6, `cp313-manylinux_2_27_x86_64` verified) | Create the venv with a Python in that range and retry; `--print-install` prints the range and warns when the current Python is outside it.
## Compilation
Symptom | Cause | Fix
------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ---
`INTERNAL error at compiler_plugin.cc` / SIGABRT during compile | Memory sharding/truncation constraints (documented in the FAQ, mostly for non-G5 targets and large models) | Retry with `--truncation-type half --sharding-intensity maximum`.
"The compiler does not support layers with dynamic shapes" | Dynamic tensor shapes | Re-export the model with static shapes, then recompile.
"does not support the specified device" | Wrong/unsupported target string | Use exactly `Tensor_G5` or `Tensor_G6` (case-sensitive).
Compile succeeds but the report shows ops left on CPU | Unsupported ops or dtypes | Check the partition report; try `--int64-to-int32`; otherwise benchmark with `--allow-cpu-fallback` and note the caveat.
`compile_model.py` exit 3 `is already compiled for Tensor_G5` (or `Tensor_G6`) | The input is itself a compiled model (the `.tflite` carries a Google Tensor stamp) | Compile the ORIGINAL (uncompiled) export instead. `--force` is not a fix: it only skips this check, and the compiler then fails with `compiled_result or num_byte_code is nullptr` (exit 6) because it cannot recompile `DISPATCH_OP` partitions.
`compile_model.py` exit 3 `was compiled by another toolchain`, `check_compiled.py` exit 4 | The input holds an Edge TPU custom op (`edgetpu-custom-op`, `edgetpu-custom-op-2`) from the Edge TPU compiler or older Google Tensor tooling: one opaque op instead of TFLite ops (observed 2026-10-14 with files named `*_compiled.tflite`, which `check_compiled.py` reported as plain before it learned this marker) | Compile the ORIGINAL model it was made from. Such files run neither on LiteRT's Google Tensor runtime nor on the CPU, so `benchmark_on_device.py` and `package_ai_pack.py` refuse them too. Without the check, the compiler logs `selected 0 ops, from a total of 1 ops` and `compiled_result or num_byte_code is nullptr`.
`compile_model.py` exit 2 `output already exists: ... stopping so it is not overwritten` | A file with the default name `<model>_Google_<target>.tflite` is already in the output directory (the script never overwrites silently) | Verify it with `scripts/check_compiled.py` and reuse it, or pick another name with `--output-name NAME`, or pass `--overwrite` if the user explicitly wants it replaced.
Model > 2 GB fails | Large-model path disabled | Add `--large-model-support`.
`compile_model.py --colab` exit 6: timed out during `colab exec` or killed (OOM) on the remote VM | Large model exceeded the default 900 s timeout or the standard Colab VM memory | Add `--colab-high-mem` (allocates a high-RAM Colab VM via `colab new --high-mem`) and/or increase `--colab-timeout 1800`.
Interrupted `--colab` run (`SIGKILL`) left a Colab VM session active | `SIGINT`, `SIGTERM`, and `SIGHUP` run the `finally:` cleanup automatically, but `SIGKILL` cannot | Check `colab sessions` and stop any leftover `litert-gt-*` session with `colab stop -s <session>`.
Vague/unknown compiler error | Limited error reporting | Retry with different flag combinations (FAQ guidance); if reproducible, file an issue on the LiteRT GitHub with the model and flags.
## adb and device
| Symptom | Cause | Fix |
|---|---|---|
| `adb not found on PATH` | platform-tools missing | Install https://developer.android.com/tools/releases/platform-tools and add to PATH. |
| `adb devices -l` prints an empty list ("no ready adb device", exit 3) | USB: cable/port or USB debugging off. Forwarded phone (serial of the form `host:port`, e.g. `localhost:41015`): the forward or `adb connect` session dropped (host sleep, SSH tunnel restart) | USB: re-plug, enable Developer options > USB debugging, accept the RSA prompt. Forwarded: `adb connect host:port` (the serial is in the user's earlier `results.json` under `device.serial`) and read its output - it exits 0 even on failure; `Connection refused` means the forward itself is down and must be re-created on the host that owns the phone (nothing on this side fixes it; retry after it is back). Prefer `adb reconnect` over `adb kill-server`, which drops every device of every user on a shared host. |
| Device listed as `unauthorized` or `offline` | USB-debugging prompt not accepted, or a stale connection | Accept the prompt on the phone, re-plug; `adb reconnect` (or `adb reconnect offline`). |
| "more than one device connected" | Several phones/emulators | Pass `--serial <id>` from `adb devices`. |
| exit 4 `model is compiled for Tensor_G6 but the device is Tensor_G5. Recompile the ORIGINAL (uncompiled) model with --target Tensor_G5; there is no runtime fallback.` (or the reverse) | Target mismatch; the script stops here, before anything is downloaded or pushed (`--output-dir` is not created) | Options, most specific first: an existing build of the same model for the phone's SoC (verify with `check_compiled.py --expect-target`), the matching phone, or a recompile of the original export. |
| With `--allow-mismatch`: model loads, delegate attaches, then every run logs `Failed to invoke SB invocation context`, `FAILED_PRECONDITION: A request is already in-flight`, `Node number 1 (DELEGATE) failed to invoke`, ending in `Benchmarking failed.` (exit 6) | A model compiled for another Tensor SoC (seen: G6 model on a G5 phone) | Recompile for the attached SoC; there is no runtime fallback. |
| `ro.soc.model` unrecognised | Unexpected device | Verify it is a Pixel 10/11; the script still runs but cannot validate the target. |
| `adb push` fails with "No space left on device" | Full phone storage | Free space or pick a different `--device-dir`. |
| User asks to clean a custom `--device-dir` that also holds their own files | Leftovers of interrupted runs are always `<base>/run-<timestamp>-<pid>/`; everything else in the base belongs to the user | `adb shell ls -la <base>` first, then remove only the `run-*` entries (by name or `rm -rf <base>/run-*`); never the base itself. The script's own run dir is created and removed per run. |
## Host-side binaries (benchmark_model, dispatch library)
| Symptom | Cause | Fix |
|---|---|---|
| exit 5 `download failed (HTTP Error 404 ...)` for `libLiteRtDispatch_GoogleTensor.so` | The chosen bucket release directory has no Google Tensor dispatch library (which directories do: the bucket table in `benchmark-flags.md`) | Use the default URLs (release from `versions.json`), or keep your `--benchmark-url` and pass `--dispatch-lib` (GitHub release zip / own build, see `benchmark-flags.md`). |
| exit 5 `download failed (<urlopen error ...>)` for either binary | No internet, or a proxy that blocks `storage.googleapis.com` | Download both files on another machine and pass `--benchmark-bin` and `--dispatch-lib`; both are plain files, no install needed. |
| `--dispatch-lib` exit 5 "not found under" / "not inside" | The directory/zip/aar does not contain `libLiteRtDispatch_GoogleTensor.so` | Point at the extracted `.so` itself (any file name is fine as long as it is an ELF shared library - it is pushed under the canonical name), or a zip that contains it. |
| `--dispatch-lib` exit 5 "is not an ELF shared library, a directory, a .zip or an .aar" | The path is a text/HTML file (e.g. a failed browser download) or something else that is not a library | Re-download the `.so`; check with `file <path>` that it is an `ELF 64-bit ... ARM aarch64` shared object. |
| Binary behaves oddly after a bucket update, or two machines report different results with the same `latest` URL | A rolling release (`latest`, `nightly`) is cached at the build that was first downloaded and never refreshed on its own | Compare the `md5` in the provenance line (`fetched <date>, md5 <hash>`) with `md5Hash` in the bucket listing `https://storage.googleapis.com/storage/v1/b/litert/o?prefix=binaries/<release>/android_arm64/`; re-run with `--refresh-binary` (re-downloads both files). `fetch date not recorded` = cached by an older script version; `--refresh-binary` adds the record. |
| exit 5 `no default download URL (cannot read .../versions.json ...)` or `(... 'binaries_release' must be ...)`, or `--print-install` exit 2 | The skill's `versions.json` is missing, not valid JSON, or has a malformed `pip_release` / `binaries_release` | Restore it from version control (format in `contributing.md`). Until then pass `--benchmark-url` (or `--benchmark-bin` + `--dispatch-lib`); compiles still run but skip the version comparison. |
## benchmark_model on the device
Symptom | Cause | Fix
------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---
"Requesting full delegation and CPU acceleration are incompatible" | `--use_cpu=true` combined with `--require_full_delegation=true` | Never combine them; the script passes `--use_cpu=false` in strict mode.
Run dies right after `Loading shared library: .../libLiteRtDispatch_GoogleTensor.so` (before `DispatchDelegate::Initialize`) | Dispatch `.so` unusable: wrong ABI/architecture, truncated download, or a build far from the runtime's release (`latest` and `2.3.0` do interoperate - verified on a Pixel 10) | Re-run with `--refresh-binary` using the defaults (binary and library from the same release directory, `binaries_release` in `versions.json`). If you pinned `--benchmark-url`, take the dispatch library from that same release.
exit 6 `benchmark_model exited 0 but printed no results in the format this script parses` (or `printed nothing`) | The binary's output differs from what the parser (`_PATTERNS` in `benchmark_on_device.py`) knows - usually a newer or older `benchmark_model`, e.g. a freshly downloaded `latest`/`nightly` | Re-run with the default URLs, or pin a release whose output parses with `--benchmark-url .../binaries/<release>/android_arm64/benchmark_model`. Fixing the skill (update `_PATTERNS` and the output block in `benchmark-flags.md`) is described in `contributing.md`. No profiler retry is attempted - it cannot fix a format change.
**Versions** line says `DIFFERENT releases`, `but SDK package X (DIFFERENT)`, or that the two runtime binaries come from different sources | The model was compiled with one LiteRT release and run with binaries from another, or the binaries were mixed | Usually still runs (nearby releases interoperate); mention it in the report's Notes. For a clean comparison use the pinned pair (`--print-install` + the default URLs) or pin `--benchmark-url` to the compile's release if that directory ships the dispatch library. A line ending `(the pair verified in versions.json)` needs no action.
Strict NPU run fails but `--allow-cpu-fallback` works | Not all ops were compiled to the TPU | Inspect the compile report; fix the model or accept mixed timing.
Run exits non-zero only with `--use_profiler=true` | Profiler unsupported for this build/model | The script already retries without the profiler (the first attempt's log is kept as `npu_profiled_attempt.log`); use `--no-profiler` to skip the first attempt.
Bare `ERROR: Benchmarking failed.` right after `Found async dispatch capabilities`, nothing else | `--signature_to_run_for` named a signature the model does not have (seen with a model that has no signature defs at all) | The script now rejects an unknown `--signature` up front (exit 2, "signature '...' not found"); omit `--signature` to run the main subgraph.
exit 6 "did not finish within --timeout Ns" | Run longer than `--timeout` (default 900 s); the script kills its adb process, which also ends `benchmark_model` on the phone | Raise `--timeout`, or reduce `--num-runs` / add `--extra-arg=--max_secs=N`. No profiler retry is attempted after a timeout.
Very high `Inference (std)` or slower than expected | Thermal throttling, screen off, background load | Check the `**Thermal before NPU run:**` header line (`throttling status N (label)` from `dumpsys thermalservice`; the sensor value next to it is a single informational reading); if the status is above 0, let the phone cool, keep the screen on, rerun; try `--performance-mode sustained_performance` for steady-state numbers.
`NPU speed-up vs CPU` is below 1x (`the CPU was faster by N.NNx`) | Tiny model: the fixed per-inference NPU dispatch cost dominates (a single-op model measured ~2.9 ms NPU vs ~0.08 ms CPU on a Pixel 10), so there is nothing to gain from the TPU for it | Not a fault - report it as measured. Real workloads (e.g. a 16 MB segmentation model: ~16 ms NPU vs ~118 ms CPU) show the expected gain.
`npu.log` contains `WARNING: [dispatch_delegate_kernel.cc:...] MediaTek dispatch API returned contradictory buffer requirements for Float32 tensor ...` on a Pixel | Generic log message in the shared dispatch-delegate code path (seen only with a tiny single-op model); the run still logs `Replacing 1 out of 1 node(s) with delegate (DispatchDelegate)` and finishes with results | Benign - the script counts it as `known-benign` in the **Log check** line; the full list of expected log lines is in `benchmark-flags.md`.
**Log check** line shows `N unexpected WARNING/ERROR lines` (N > 0) on a run that exited 0 | `benchmark_model` logged something outside the known-benign list (new runtime message, partial delegation with `--allow-cpu-fallback`, a failed `--cpu-baseline`, ...) | Read the **Unexpected log lines** section under the table (verbatim lines, `(xN)` = repeats). Match them against this file and `benchmark-flags.md`; quote the ones you cannot explain in the report's Notes. The table values are still real measurements.
exit 2 `--cpu-baseline must be the ORIGINAL uncompiled .tflite` (before anything is pushed) | A compiled model was passed as the baseline; compiled models contain NPU-only `DISPATCH_OP` nodes and cannot run on the CPU | Pass the original uncompiled `.tflite` to `--cpu-baseline` (the compiled file stays as `--model`).
exit 2 `is not AOT-compiled (no DISPATCH_OP/LiteRtStamp)` | An uncompiled model was passed as `--model`; the strict NPU run needs a Google Tensor-compiled file | Compile it first (SKILL.md step 2b), then benchmark the compiled output; the uncompiled file is only valid for `--cpu-baseline`.
"Runs (warmup / measured)" shows more runs than `--warmup-runs` / `--num-runs` | `benchmark_model` treats those as minimums and also enforces `--warmup_min_secs` (0.5 s) / `--min_secs` (1 s); fast models hit the time floor first | Expected; report the actual counts. For exact counts: `--extra-arg=--min_secs=0 --extra-arg=--warmup_min_secs=0`.
Interrupted run left files on the phone | Process killed with SIGKILL (Ctrl-C, SIGTERM and SIGHUP all run the cleanup; verified on device) | `adb shell ls -la /data/local/tmp/litert_benchmark` first, then `adb shell rm -rf /data/local/tmp/litert_benchmark/run-*` (removes only this skill's per-run directories; never remove the base directory itself, which can hold the user's own files).
`**TPU tile time:** unavailable - the dispatch library returned no telemetry hook ('Accelerator returned null hooks.') ...` | The dispatch library has no telemetry hooks: builds from the LiteRT GitHub source compile them out | Use the default bucket binaries (they have the hooks: `2.3.0` and `latest`, checked 2026-10-09; `2.3.1`, checked 2026-10-26), or skip the pass with `--no-tile-time`. The NPU numbers are unaffected.
`**TPU tile time:** inconsistent - ... the hook counted N calls for R runs, which matches no known pattern ...` | The hook's count is not (1 + D), D or 1 times the runs: e.g. a multi-signature model whose first `Replacing ...` line belongs to another subgraph, or a hook build that counts differently | Report the header's total, not a per-inference value, and say why in the Notes. If a new release changed the counting, see `contributing.md`.
`**TPU tile time:** failed - the tile-time pass failed (exit N)` or `timed out` | The hooked second pass crashed or timed out; the NPU run itself succeeded | Read `tile_time.log`; rerun, or use `--no-tile-time --no-power`.
`**TPU energy:** unavailable - this dispatch library's power hook predates the fix ...` | The dispatch library carries the old power hook (checked before the pass: e.g. the Maven `litert-npu-runtime-google-tensor` 2.3.0 AAR passed as `--dispatch-lib`, checked 2026-10-26, or a cache from before the 2026-10-23 re-upload of `2.3.1`), which reads the energy counter around every call and double counts | Use the default binaries (`--refresh-binary` if the cached library is old). An app's own library (`.aab`, runtime `.aar`) has the old hook if it is from runtime 2.3.0 (the 2.3.2 AAR has the fixed one, checked 2026-10-27): moving the app to the pinned runtime release (`maven_release`) brings the fix. Latency and tile time are unaffected; the energy row shows `-`.
`**TPU energy:** unavailable - the power hook could not read the TPU energy counter: '...'` | The phone did not let the shell process read its on-device power monitor; the quoted line is the hook's own message | Report the quoted line in the Notes. Nothing in the skill fixes it; latency and tile time are unaffected.
`**TPU energy:** unreliable - ... 2 calls per run, the pattern of the old power hook ...` | An old power hook that the pre-check did not recognise | As for the old-hook row above; never quote its total as an energy.
`tile_time.log` / `tile_time_report.txt` say `Average TPU tile time (us): X`, about half the table's TPU tile time | An older dispatch library (`2.3.0`, or `2.3.1` as first uploaded on 2026-10-20) counts every inference 1 + D times (2x for a normal compiled model) but adds tile time once; the header then says `2 calls per run` | Quote the table value; the script divides the total by the real runs. If the run used the pinned release, the cached library predates a re-upload: compare the Dispatch library md5 with `verified.binaries` in `versions.json` and rerun with `--refresh-binary`.
## Packaging for an app (`package_ai_pack.py`, the app build)
| Symptom | Cause | Fix |
|---|---|---|
| `package_ai_pack.py` exit 5 `LiteRT's AI-pack exporter is not importable` | Started with a Python that has no `ai-edge-litert` (e.g. the system `python3`) | Run it with the compile venv's interpreter, or create a venv with `ai-edge-litert` at the pinned version (the message prints the line; the Beta SDK is not needed). |
| `package_ai_pack.py` exit 5 `LiteRT's AI-pack exporter failed (...)` | The installed `ai-edge-litert` differs from the pin and its `export_lib` API changed | Install the pinned version (`compile_model.py --print-install`). If it already is the pin, `export_lib` changed in a way the skill does not know yet: see `contributing.md`. |
| exit 3 `--fallback ... is a compiled build` / `--compiled ... is not compiled for Google Tensor` | The two inputs were swapped, or the original was compiled in place | `--fallback` is the ORIGINAL uncompiled model, `--compiled` the `*_Google_Tensor_G*.tflite` builds (`check_compiled.py` tells them apart). |
| exit 2 `two --compiled builds for Tensor_G5` | Two builds stamped for the same SoC | Pass one build per SoC (the one that was benchmarked). |
| exit 2 `differs from the build its .compile.json describes` | The file changed after compiling, or the sidecar belongs to another build | Package the build that was compiled and benchmarked, or recompile. |
| exit 2 `was compiled from a different file than --fallback` | `--fallback` is not the model the build was compiled from, so the CPU and TPU paths would run different models | Pass the original from the build's sidecar (`input`); add `--allow-source-mismatch` only if that difference is intended. |
| exit 2 `output already exists` / `refusing to replace` | The output directory exists; the script replaces only packages it wrote itself | Pick another `--output-dir`, or `--overwrite` for an earlier package (it has a `pack.json` from the script). |
| exit 7 `post-export verification failed` | The exporter wrote something the checks do not expect (new LiteRT behaviour) or a template is out of sync | Nothing was left at `--output-dir`. Note the message and see `contributing.md` (the self-test reproduces it). |
| Gradle: `Plugin with id 'com.android.ai-pack' not found` | Android Gradle plugin older than 8.8, or not declared in the root `build.gradle(.kts)` | Use AGP 8.10 or newer (device targeting needs 8.10) and declare it at the root with `apply false`. |
| Kotlin: `class 'com.google.ai.edge.litert....' was compiled with an incompatible version of Kotlin. The actual metadata version is X, but the compiler version Y can read versions up to Z` | The app's Kotlin Gradle plugin is older than the Kotlin LiteRT's Kotlin API was built with (observed: LiteRT 2.3.0 needs Kotlin 2.3) | Use Kotlin `kotlin_min` from `versions.json` or newer; the package's `INTEGRATION.md` names the version. |
| Gradle: device targeting settings rejected or ignored | `android.experimental.enableDeviceTargetingConfigApi=true` missing in `gradle.properties` | Add it (INTEGRATION.md step 7). |
| Gradle `packageDebugBundle` / `packageReleaseBundle`: `All modules with native libraries must support the same set of ABIs, but module 'base' supports '[ARM64_V8A, ARMEABI_V7A, X86_64]' and module 'google_tensor_runtime' supports '[ARM64_V8A]'` | The app builds every ABI of LiteRT's native libraries, but the Google Tensor runtime has only arm64-v8a | Limit the app to arm64-v8a: `ndk { abiFilters.add("arm64-v8a") }` in `defaultConfig` (INTEGRATION.md step 6). Ask first: devices without arm64-v8a can then no longer install the app. |
| bundletool: `Module '...' refers to device groups [...] which are not in the list [...]` | The app's `device_targeting_configuration.xml` does not define a group that the AI pack or the runtime module uses | Copy the XML from the package, or merge its `<config:device-group>` elements into the app's XML unchanged. |
| bundletool: `All modules with device group targeting must support the same set of groups` | Several AI packs were packaged for different SoC sets | Package every model for the same SoCs (e.g. G5 and G6 for all), or keep one pack per app. |
| bundletool `build-apks`: `Could not extract aapt2 ... providing the path to aapt2 using the flag --aapt2` | A bundletool jar without aapt2 (the `com.android.tools.build:bundletool` artifact from Google Maven; observed with 1.18.3) | Use `bundletool-all-<version>.jar` from https://github.com/google/bundletool/releases, or add `--aapt2=<Android SDK>/build-tools/<version>/aapt2`. |
| App log `LITERT_TENSOR_RESULT {"path":"cpu","npu_error":"not a packaged Google Tensor device ..."}` | Expected on phones without a packaged SoC, and on Android builds without NPU support (LiteRT's Google Tensor check needs API 36 and a build ID not starting with `BP2A`) | Nothing to fix; the CPU model runs. |
| App log `"path":"cpu"` with another `npu_error` on a packaged Pixel | Runtime split missing, native libraries not extracted, or mismatched LiteRT releases | `adb shell pm path <app id>` must list the `google_tensor_runtime` split (install with `--device-groups=<group>` in local testing); set `useLegacyPackaging = true`; keep `litert` and `litert-npu-runtime-google-tensor` on one release. |
| `on-demand` / `fast-follow` pack never arrives in local testing | Packs come from the APK set pushed by `bundletool install-apks --local-testing`; updates are not supported | Uninstall the app, rebuild the APKs with `--local-testing`, reinstall. |
| Quick test: `./gradlew installDebug -PtensorQuickTest=<SoC>` runs the model on the CPU (`"path":"cpu"`) | `<app module>/tensor_quick_test/<SoC>/assets/` is missing (Gradle silently ignores a missing source folder), `<SoC>` is not the phone's, the Gradle block is not in the app module's build file, or `useLegacyPackaging` is not `true` | Copy the package's `quick_test/` there; use the phone's SoC with an underscore (`adb shell getprop ro.soc.model`: `Tensor G5` -> `Tensor_G5`); check the block and the packaging setting (INTEGRATION.md, "Optional: quick test without bundletool"). The `npu_error` in the log line says which. |
### Updating an app (`--update-project`)
| Symptom | Cause | Fix |
|---|---|---|
| exit 2 `no settings.gradle.kts or settings.gradle in ...` | `--update-project` names a module or another folder, not the project root | Pass the folder with the settings file; the message names it when a parent has one. |
| exit 2 `no AI pack with Google Tensor builds in ...` | The app has no AI pack with Google Tensor device-group folders | It is a new integration: run without `--update-project` and follow `INTEGRATION.md` (SKILL.md step 5a). |
| exit 2 `several AI packs ship Google Tensor builds` / `holds several models` | The project has more than one candidate | Pass `--pack-name` / `--model-name` with one of the names the message lists. |
| exit 2 `device group ... selects several SoCs` | One group lists several `system-on-chip` selectors, but a compiled build runs on one SoC only | Give each SoC its own group, as LiteRT's exporter does, then re-run. |
| exit 2 `cannot tell where the app keeps the original (CPU) model` | The CPU copy is neither in the pack's `#group_other` folder nor at `litert/<model>_cpu_gpu.tflite` or the loader's `CPU_MODEL_ASSET` | `--cpu-asset <path in the project>` (the message lists the models it found), or `--cpu-asset none` if the app has no CPU copy. |
| exit 2 `uses <mode> delivery ... --update-project keeps it` | `--delivery` differs from the pack's `deliveryType` | Drop `--delivery`. To change the mode, edit `deliveryType` in the pack's build file first (and add the permissions a new package's `INTEGRATION.md` lists for `fast-follow` / `on-demand`). |
| exit 7 `changed in the project while the update was prepared` | A project file changed during the run | Re-run when the project is not being edited. |
| Verdict `structural`, `Model inputs/outputs` = `edit` | The new model's inputs or outputs differ in shape, type or count from the app's CPU copy | Update the app's pre- and post-processing (`model_io.json` lists the new ones) together with the files. |
| `Runtime` = `device` | The app's runtime is not `maven_release`, or its version could not be read | Run the strict benchmark with the app's library: `benchmark_on_device.py --dispatch-lib <app .aab, runtime .aar or .so>` (UPDATE.md section 4). If it fails, upgrade `litert` and the runtime together. |
| After copying, the dry run still shows `replace` | A file was not copied, or was copied to another path | Copy the rows still marked `replace` from `files/<path>`; paths are relative to the project root. |
### Applying the plan (`--check-project`) and checking on a Pixel (`install_and_verify.py`)
| Symptom | Cause | Fix |
|---|---|---|
| `--check-project` exit 2 `no readable pack.json` / `was not written by package_ai_pack.py` | `--package` is not a folder that `package_ai_pack.py` wrote | Pass the package folder (the one with `INTEGRATION.md` and `pack.json`), by default `<model dir>/app_package/<name>`. |
| `--check-project` exit 2 `no app module :<name> in ... (app modules found: ...)` | The project has no module by the package's (or `--app-module`'s) name, and not exactly one app module | Pass `--app-module` with one of the modules the message lists. |
| `--check-project` `NOTE: the package was made for the app module :app; this project's app module is ...` | The package was written for another app module name; its runtime module depends on that module | Re-package with `--app-module <the project's app module>` (SKILL.md step 5a), then check again. |
| `--check-project` exit 1 | Requirements of `INTEGRATION.md` are not met yet: this is the plan, not an error | Apply the `fail` items once the user approves (SKILL.md step 6); risky items need their own OK. |
| `--check-project` warns `no minSdk in ...`, `Android Gradle plugin: version not found` or `Kotlin: version not found` | The value is set outside the files the check reads (a convention plugin, `buildSrc`, a variable from another file) | Check it by hand: `minSdk` 31 or higher, the Android Gradle plugin 8.10 or newer, Kotlin `kotlin_min` or newer (`INTEGRATION.md` names the version). |
| `--check-project` `Kotlin: the app module applies no Kotlin plugin` | A Java-only app; `TensorModelLoader.kt` is Kotlin | Adding Kotlin is a risky item: ask first. With the Android Gradle plugin 9 or newer it is only a warning, because the plugin can compile Kotlin itself. |
| `install_and_verify.py` exit 2 `adb not found` / `java not found` / `Gradle not found` | The Android SDK platform-tools, a JDK or the Gradle wrapper is missing | Install platform-tools, set `JAVA_HOME` to a JDK the project's Gradle supports, and use a project with `./gradlew` (or pass `--gradle`). |
| `install_and_verify.py` exit 2 `need exactly one device, found ...` | No phone, a phone that has not accepted USB debugging, or several phones | Connect the Pixel and accept the prompt, or pass `--serial`. |
| `install_and_verify.py` exit 2 `cannot tell the app module` | Several modules (or none) apply `com.android.application` | Pass `--app-module`. |
| `install_and_verify.py` exit 3 `the Gradle build failed` | The project does not build: often a JDK its Gradle does not support (`Unsupported class file major version`), or a mistake in an edit | Read `gradle.log` in the output folder. Use a supported JDK; fix errors the edits caused, and report errors that were there before. |
| `install_and_verify.py` exit 3 `the build wrote no .aab to .../bundle/debug` | The app has product flavors, so its bundles are per flavor (`bundle/freeDebug/`, ...) | Pass `--variant <flavor>Debug`, for example `--variant freeDebug`. |
| `install_and_verify.py` exit 4 `cannot download .../bundletool-all-...jar` | No internet, or GitHub is blocked | Download a `bundletool-all` jar elsewhere and pass `--bundletool <jar>` (a folder with bundletool and its dependencies from Google Maven also works). |
| `install_and_verify.py` exit 4 `bundletool install-apks failed` | The phone refused the APK set, e.g. `INSTALL_FAILED_OLDER_SDK` (the app's `minSdk` is above the phone's API level) or too little storage | Read `install_apks.log` in the output folder. |
| `install_and_verify.py` exit 6 (no result line) | The app did not call `TensorModelLoader.load()` within `--timeout`, or it crashed | Open the screen that uses the model while the script waits, or raise `--timeout`. For a crash: `adb logcat -b crash -d`. |
| `install_and_verify.py` exit 7 `is already installed` | Local testing cannot update an installed app | Ask the user (uninstalling deletes the app's data on the phone), then rerun with `--uninstall-first`. |
| `install_and_verify.py` exit 1 and `Dispatch library on the phone: NO` | The runtime split is missing from `Installed:`, or native libraries are not extracted | Check the device groups and `useLegacyPackaging = true`: `--check-project` reports both. |
| `Expected path: CPU (Android API ...; the NPU needs API 36 or newer)` or `(build ... has no NPU support)` | The phone's Android build does not support the Google Tensor NPU | Not an app problem; the CPU result is correct there. Update the phone, or test on another one. |
benchmark_on_device.py 83.4 KB
#!/usr/bin/env python3
# Copyright 2026 The Google AI Edge Authors. All Rights Reserved.
#
# 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.
"""Benchmarks a Google Tensor-compiled .tflite on an attached Pixel over adb.
What it does (all steps are synchronous; nothing is left running):
1. Picks the adb device (or uses --serial), reads its SoC and checks that the
model was compiled for it (``ro.soc.model`` -> ``Tensor_G5`` etc.).
2. Resolves ``libLiteRtDispatch_GoogleTensor.so`` (--dispatch-lib: a .so, a
directory, or a .zip/.aar that contains it; default: cached download from
the public LiteRT binaries bucket) and the android_arm64
``benchmark_model`` binary (--benchmark-bin, else a cached download from
the same bucket directory, so the two always come from one release). The
default release is ``binaries_release`` in the skill's versions.json;
each download's fetch date and md5 are recorded next to it and printed.
3. Pushes model + binary + dispatch library to a fresh per-run directory
/data/local/tmp/litert_benchmark/run-<timestamp>-<pid>/ (never overwrites
or deletes files that were already on the phone).
4. Runs an NPU-only benchmark:
benchmark_model --graph=... --use_npu=true --use_cpu=false
--require_full_delegation=true
--dispatch_library_path=<device dir>
--num_runs=<--num-runs, default 50>
--warmup_runs=<--warmup-runs, default 5>
--report_peak_memory_footprint=true --use_profiler=true
then the same NPU run once more, without profiler and memory monitor,
with LITERT_VENDOR_HOOK_ARGS enabling the dispatch library's TPU
tile-time and power hooks (--no-tile-time / --no-power turn them off;
with both, this pass is skipped); and, with --cpu-baseline
<original.tflite>, a CPU run of the uncompiled model for comparison.
5. Parses the results, prints a Markdown header + table in which every value
comes from the device or this run (device props, thermal status before
the NPU run, the ``<model>.compile.json`` sidecar written by
compile_model.py if present, a Versions line comparing the sidecar's
LiteRT version with the release of the runtime binaries, the runtime
"Replacing N out of M node(s)" delegation line, all timings, TPU tile time
per inference (the hook's total divided by the runs benchmark_model made:
older dispatch libraries count each inference 1 + D times, which makes
the hook's own average wrong), TPU energy per inference (the power hook's
TPU rail energy over the hooked pass divided by its runs; not measured
with a dispatch library whose power hook predates the fix), and a log
check that counts the known-benign WARNING lines and lists any other
WARNING/ERROR line verbatim), writes
results.json, report.md (the same block), npu.log, cpu.log,
tile_time.log (the hooked pass), tile_time_report.txt / power_report.txt
(the hooks' reports), npu_profile.txt / cpu_profile.txt to --output-dir,
and deletes the per-run directory it created on the device (also on
failure) unless --keep-device-files is given.
Standard library only; needs ``adb`` on PATH and a device with USB debugging.
Exit codes
----------
0 success 4 model/device SoC mismatch (see --allow-mismatch)
2 bad arguments 5 dispatch library or benchmark binary unavailable
3 adb/device problem 6 benchmark_model failed on device, or exited 0 with
output this script cannot parse (format change)
"""
from __future__ import annotations
import argparse
import datetime
import hashlib
import json
import os
import pathlib
import re
import shlex
import shutil
import signal
import subprocess
import sys
import tempfile
from typing import Any
import urllib.error
import urllib.request
import zipfile
DEFAULT_DEVICE_DIR = "/data/local/tmp/litert_benchmark"
# Public LiteRT prebuilt binaries. The same directory holds benchmark_model and
# libLiteRtDispatch_GoogleTensor.so built together, so a release directory
# ("latest", "nightly" or a version) is the unit of versioning. The default
# release is "binaries_release" in the skill's assets/versions.json, its single
# source of versions (see references/contributing.md); which release
# directories ship the Google Tensor dispatch library is listed in
# references/benchmark-flags.md.
BINARIES_BUCKET = "https://storage.googleapis.com/litert/binaries"
VERSIONS_FILE = (
pathlib.Path(__file__).resolve().parent.parent / "assets" / "versions.json"
)
def _read_versions() -> tuple[dict[str, Any], str | None]:
"""Returns (versions.json contents, None) or ({}, error text).
Never raises: --help, --dry-run and runs with local binaries must work even
if the file is missing or broken; only a default download needs it.
"""
try:
data = json.loads(VERSIONS_FILE.read_text(encoding="utf-8"))
except (OSError, ValueError) as e:
return {}, f"cannot read {VERSIONS_FILE}: {e}"
release = data.get("binaries_release") if isinstance(data, dict) else None
if not isinstance(release, str) or not re.fullmatch(
r"[A-Za-z0-9._-]+", release
):
return {}, (
f"{VERSIONS_FILE}: 'binaries_release' must be a bucket "
"release directory name such as 'latest' or 'X.Y.Z'"
)
return data, None
VERSIONS, VERSIONS_ERROR = _read_versions()
DEFAULT_BINARIES_DIR = (
f"{BINARIES_BUCKET}/{VERSIONS['binaries_release']}/android_arm64"
if VERSIONS
else None
)
DEFAULT_BENCHMARK_URL = (
f"{DEFAULT_BINARIES_DIR}/benchmark_model" if DEFAULT_BINARIES_DIR else None
)
DISPATCH_LIB_NAME = "libLiteRtDispatch_GoogleTensor.so"
CACHE_DIR = pathlib.Path(
os.environ.get(
"LITERT_GOOGLE_TENSOR_CACHE",
pathlib.Path.home() / ".cache" / "litert-google-tensor",
)
)
DISPATCH_LIB_ENV = "LITERT_GOOGLE_TENSOR_DISPATCH_LIB"
# ``adb shell getprop ro.soc.model`` values (case-insensitive) -> AOT target.
SOC_PROP_TO_TARGET = {
"tensor g3": "Tensor_G3",
"tensor g4": "Tensor_G4",
"tensor g5": "Tensor_G5",
"tensor g6": "Tensor_G6",
}
PERFORMANCE_MODES = (
"extreme_power_saver",
"power_saver",
"balanced",
"high_performance",
"sustained_performance",
"burst",
)
TFLITE_FILE_IDENTIFIER = b"TFL3"
DISPATCH_OP_MARKER = b"DISPATCH_OP"
BUILD_STAMP_KEY = b"LiteRtStamp"
# Custom op of models compiled by the Edge TPU compiler (and older Google
# Tensor tooling), same check as check_compiled.py.
LEGACY_TPU_OP_RE = re.compile(rb"edgetpu-custom-op[\w-]*")
SOC_MODEL_RE = re.compile(rb"Tensor_G\d+")
_DISPATCH_DIR_TEXT = (
DEFAULT_BINARIES_DIR or f"{BINARIES_BUCKET}/<release>/android_arm64"
)
DISPATCH_LIB_HELP = f"""\
{DISPATCH_LIB_NAME} is the on-device Google Tensor runtime library that
benchmark_model loads for --use_npu. Ways to provide it:
1. Let this script download it from the same public directory as
benchmark_model (default; see --benchmark-url / --dispatch-url):
{_DISPATCH_DIR_TEXT}/{DISPATCH_LIB_NAME}
2. Pass --dispatch-lib with the .so, a directory, or a .zip/.aar containing
it (e.g. LiteRT GitHub release assets:
https://github.com/google-ai-edge/LiteRT/releases),
or export {DISPATCH_LIB_ENV}=<path>.
3. Build it from source ('How do I build a Google Tensor dispatch library?'):
https://developers.google.com/edge/tensor-sdk/tensor-faqs
Keep the dispatch library and benchmark_model from the same LiteRT release."""
class BenchmarkError(Exception):
def __init__(self, code: int, message: str):
super().__init__(message)
self.code = code
# --------------------------------------------------------------------------
# Helpers
# --------------------------------------------------------------------------
def inspect_model(path: pathlib.Path) -> dict[str, Any]:
data = path.read_bytes()
compiled = DISPATCH_OP_MARKER in data and BUILD_STAMP_KEY in data
return {
"is_tflite": len(data) >= 8 and data[4:8] == TFLITE_FILE_IDENTIFIER,
"compiled": compiled,
"soc_models": sorted({m.decode() for m in SOC_MODEL_RE.findall(data)}),
"size_bytes": len(data),
# Compiled by another toolchain (Edge TPU custom op), not by LiteRT.
"legacy_ops": [] if compiled else sorted(
{m.decode() for m in LEGACY_TPU_OP_RE.findall(data)}),
}
def legacy_model_error(path: pathlib.Path, ops: list[str], role: str) -> str:
return (
f"ERROR: {role} {path.name} was compiled by another toolchain: it holds "
f"an Edge TPU custom op ({', '.join(ops)}), which neither the Google "
"Tensor runtime nor the CPU can run (check_compiled.py exits 4 for such "
"files). Use the ORIGINAL model it was made from: compile it with "
"scripts/compile_model.py for --model, or pass it as is for "
"--cpu-baseline."
)
def safe_name(path: pathlib.Path) -> str:
return re.sub(r"[^A-Za-z0-9._-]", "_", path.name)
def fmt_size(num_bytes: int) -> str:
"""'8,110,864 bytes (8.1 MB)'; MB = 10^6 bytes, same as the other scripts."""
text = f"{num_bytes:,} bytes"
if num_bytes >= 100_000:
text += f" ({num_bytes / 1e6:.1f} MB)"
return text
def read_compile_sidecar(model: pathlib.Path) -> dict[str, Any] | None:
"""Loads ``<model>.compile.json`` (written by compile_model.py) if present."""
sidecar = model.with_name(model.name + ".compile.json")
if not sidecar.is_file():
return None
try:
data = json.loads(sidecar.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
return data if isinstance(data, dict) else None
# android.os.Temperature throttling status values.
THERMAL_STATUS_LABELS = {
0: "none",
1: "light",
2: "moderate",
3: "severe",
4: "critical",
5: "emergency",
6: "shutdown",
}
_THERMAL_STATUS_RE = re.compile(r"Thermal Status:\s*(\d+)")
# Temperature{mValue=45.0, mType=9, mName=TPU, mStatus=0}; mType 9 = NPU.
_THERMAL_NPU_RE = re.compile(
r"Temperature\{mValue=(-?[\d.]+), mType=9, mName=([^,}]+)"
)
def read_thermal(adb: "Adb") -> dict[str, Any]:
"""Best-effort snapshot of ``dumpsys thermalservice`` (never raises)."""
info = {
"status": None,
"status_label": "unavailable",
"npu_temp_c": None,
"npu_sensor": None,
}
if adb.dry_run:
return info
try:
out = adb.shell("dumpsys thermalservice", check=False, timeout=30).stdout
except Exception: # pylint: disable=broad-exception-caught
return info
m = _THERMAL_STATUS_RE.search(out or "")
if m:
info["status"] = int(m.group(1))
info["status_label"] = THERMAL_STATUS_LABELS.get(info["status"], "unknown")
m = _THERMAL_NPU_RE.search(out or "")
if m:
info["npu_temp_c"] = float(m.group(1))
info["npu_sensor"] = m.group(2).strip()
return info
def thermal_text(t: dict[str, Any]) -> str:
if t["status"] is None:
return "unavailable (dumpsys thermalservice gave no status)"
text = f"throttling status {t['status']} ({t['status_label']})"
if t["npu_temp_c"] is not None:
text += (
f"; {t['npu_sensor']} sensor {t['npu_temp_c']:.1f} C "
"(single reading, informational)"
)
return text
# --------------------------------------------------------------------------
# TPU tile time (dispatch-library hook)
# --------------------------------------------------------------------------
# libLiteRtDispatch_GoogleTensor.so runs vendor hooks when
# LITERT_VENDOR_HOOK_ARGS (a config file path, or the config text) is set.
# Only the tile-time metric is enabled. Older dispatch libraries count every
# inference 1 + D times (once from the LiteRT runtime, once per dispatch
# invoke; D = dispatch nodes) but add tile time only on the dispatch path, so
# their own "Average" is wrong; fixed ones count once per dispatch invoke. The
# script divides the total by the runs benchmark_model really made, which is
# right for both.
HOOK_ENV = "LITERT_VENDOR_HOOK_ARGS"
HOOK_CONFIG_NAME = "tpu_hooks.textproto"
TILE_REPORT_NAME = "tpu_tile.txt"
POWER_REPORT_NAME = "tpu_power.txt"
_TILE_TOTAL_RE = re.compile(r"Total TPU tile time \(us\):\s*(\d+)")
_TILE_COUNT_RE = re.compile(r"Total inferences:\s*(\d+)")
_HOOKS_REGISTERED = "Successfully retrieved and registered vendor hooks"
_HOOKS_NULL = "Accelerator returned null hooks"
# Power metric (power_config): the TPU rail's energy counter of the phone's
# on-device power monitor. The fixed hook reads it when the first dispatch
# invoke starts and when the model is torn down, and counts dispatch invokes.
# Older builds read it around every call (several-fold slower inference) and
# count every inference 1 + D times; their numbers cannot be corrected, so the
# metric stays off for a library that carries this log string of the old code.
_POWER_TOTAL_RE = re.compile(r"Total Energy \(uJ\):\s*(\d+)")
_POWER_COUNT_RE = re.compile(r"Inference count:\s*(\d+)")
_POWER_OLD_MARKER = b"failed HandlePowerRuntimeStop"
_POWER_FAILURE_RE = re.compile(
r"^.*(?:HandlePowerRuntime|ODPM|Final energy|Skipping power metrics|"
r"PowerStats|RailEnergyData).*$",
re.M,
)
_OLD_POWER_HOOK_REASON = (
"this dispatch library's power hook predates the fix: it reads the TPU "
"energy counter around every call (several-fold slower inference) and "
"counts every inference 1 + D times, so its numbers are not usable and "
"the power metric was not enabled; the default bucket binaries carry the "
"fixed hook"
)
def hook_config(device_dir: str, tile: bool, power: bool) -> str:
"""Hook config enabling the TPU tile-time and/or the power (energy) metric.
The hook strips all whitespace and matches keys as plain substrings, so only
lowercase ``true`` enables a metric, a commented-out key would still count,
and the dump paths must not contain whitespace (main() checks that).
Args:
device_dir: Per-run directory path on the device.
tile: Whether to enable the TPU tile-time metric.
power: Whether to enable the power metric (TPU energy).
Returns:
Textproto content for the vendor hook configuration file.
"""
tile_path = f"{device_dir}/{TILE_REPORT_NAME}"
power_path = f"{device_dir}/{POWER_REPORT_NAME}"
text = ""
if tile:
text += (
"tpu_tile_time_metrics_config {\n"
" dump_tpu_tile_time_metrics: true\n"
f' tpu_tile_time_metrics_dump_path: "{tile_path}"\n'
"}\n"
)
if power:
text += (
"power_config {\n"
" dump_power_metrics: true\n"
f' power_dump_path: "{power_path}"\n'
"}\n"
)
return text
def power_hook_is_old(lib: pathlib.Path) -> bool:
"""True if the dispatch library carries the pre-fix power hook."""
try:
return _POWER_OLD_MARKER in lib.read_bytes()
except OSError:
return False # not downloaded yet (--dry-run): the pass checks the count
class Adb:
"""Minimal adb wrapper bound to one device serial."""
def __init__(self, serial: str | None, dry_run: bool):
self.serial = serial
self.dry_run = dry_run
self.adb = shutil.which("adb")
if not self.adb:
raise BenchmarkError(
3,
"adb not found on PATH. Install Android platform-tools: "
"https://developer.android.com/tools/releases/platform-tools",
)
def _base(self) -> list[str]:
return [self.adb] + (["-s", self.serial] if self.serial else [])
def run(
self,
*args: str,
timeout: int = 120,
check: bool = True,
capture: bool = True,
) -> subprocess.CompletedProcess[str]:
"""Runs ``adb [-s <serial>] <args>``; in dry-run mode only prints it.
Args:
*args: Arguments to adb, e.g. ``"shell", "getprop"``.
timeout: Seconds before subprocess.TimeoutExpired is raised.
check: Whether a non-zero exit code raises BenchmarkError.
capture: Whether to capture adb's stdout and stderr (merged) as text
instead of letting adb print to this script's output.
Returns:
The finished process; in dry-run mode a stand-in with exit code 0 and
empty output.
Raises:
BenchmarkError: If ``check`` is set and adb exits with a non-zero code.
"""
cmd = self._base() + list(args)
if self.dry_run:
print(" [dry-run] " + " ".join(shlex.quote(c) for c in cmd))
return subprocess.CompletedProcess(cmd, 0, "", "")
proc = subprocess.run(
cmd,
text=True,
timeout=timeout,
stdout=subprocess.PIPE if capture else None,
stderr=subprocess.STDOUT if capture else None,
check=False,
)
if check and proc.returncode != 0:
raise BenchmarkError(
3,
f"adb command failed ({proc.returncode}): "
f"{' '.join(cmd)}\n{(proc.stdout or '').strip()}",
)
return proc
def shell(
self, command: str, timeout: int = 120, check: bool = True
) -> subprocess.CompletedProcess[str]:
return self.run("shell", command, timeout=timeout, check=check)
def getprop(self, name: str) -> str:
if self.dry_run:
return ""
return self.shell(f"getprop {name}", check=False).stdout.strip()
def list_devices(adb_path: str) -> list[tuple[str, str]]:
out = subprocess.run(
[adb_path, "devices"], text=True, capture_output=True, check=False
).stdout
devices = []
for line in out.splitlines()[1:]:
parts = line.split()
if len(parts) >= 2:
devices.append((parts[0], parts[1]))
return devices
def pick_device(serial: str | None) -> str:
"""Returns the serial of the adb device to use.
Args:
serial: The --serial value, or None to pick the only ready device.
Raises:
BenchmarkError: If adb is missing, ``serial`` is not connected or not
ready, or (without ``serial``) not exactly one device is ready.
"""
adb_path = shutil.which("adb")
if not adb_path:
raise BenchmarkError(3, "adb not found on PATH.")
devices = list_devices(adb_path)
if serial:
for s, state in devices:
if s == serial:
if state != "device":
raise BenchmarkError(
3,
f"device {serial} is '{state}', not ready "
"(accept the USB-debugging prompt on the phone).",
)
return serial
raise BenchmarkError(3, f"device {serial} not found in `adb devices`.")
ready = [s for s, state in devices if state == "device"]
if not ready:
states = ", ".join(f"{s} ({st})" for s, st in devices) or "none"
raise BenchmarkError(
3,
"no ready adb device. Connected: "
+ states
+ ". USB: re-plug, enable USB debugging and accept the "
"prompt. Forwarded phone (serial host:port): run "
"`adb connect host:port` again; use `adb reconnect` "
"rather than `adb kill-server` on shared hosts.",
)
if len(ready) > 1:
raise BenchmarkError(
3,
"more than one device connected; pass --serial one of: "
+ ", ".join(ready),
)
return ready[0]
def _sha256(path: pathlib.Path) -> str:
digest = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def _gcs_hashes(headers) -> dict[str, str]:
"""{'md5': ..., 'crc32c': ...} (base64) from GCS ``x-goog-hash`` headers."""
hashes = {}
for value in headers.get_all("x-goog-hash") or []:
for part in value.split(","):
name, sep, digest = part.strip().partition("=")
if sep and digest:
hashes[name.lower()] = digest
return hashes
def _meta_path(cached: pathlib.Path) -> pathlib.Path:
return cached.with_name(cached.name + ".json")
def _read_download_meta(cached: pathlib.Path) -> dict[str, Any] | None:
"""The metadata written next to a download, if it belongs to this file."""
try:
meta = json.loads(_meta_path(cached).read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
if (
not isinstance(meta, dict)
or meta.get("size_bytes") != cached.stat().st_size
):
return None # unreadable, or written for another copy of the file
return meta
def _fetch_text(meta: dict[str, Any] | None) -> str:
"""'fetched <UTC time>, md5 <base64>' for the provenance line."""
if not meta:
return (
"fetch date not recorded; --refresh-binary re-downloads and records it"
)
when = str(meta.get("fetched_at", "?"))
when = when.replace("T", " ").replace("Z", " UTC")
if meta.get("gcs_md5"):
return f"fetched {when}, md5 {meta['gcs_md5']}"
return f"fetched {when}, sha256 {str(meta.get('sha256', '?'))[:16]}"
def _cached_download(
url: str | None, refresh: bool, dry_run: bool, manual_flag: str
) -> tuple[pathlib.Path, str]:
"""Downloads ``url`` into the cache once; returns (path, provenance).
Next to each download, ``<file>.json`` records the URL, the UTC fetch time,
the SHA-256 and the bucket's generation/md5 (GCS response headers), so a
cached copy of a rolling release ('latest', 'nightly') stays identifiable:
its md5 can be compared with the bucket listing's ``md5Hash``.
Args:
url: File to download, or None if there is no default URL.
refresh: Whether to download again even if a cached copy exists.
dry_run: Whether to only print what would be downloaded.
manual_flag: Flag that the error message suggests for passing a local
copy instead, e.g. ``--benchmark-bin``.
Returns:
(cache path of the file, provenance text for the report); with
``dry_run`` and no cached copy, the path does not exist yet.
Raises:
BenchmarkError: If ``url`` is None or empty, or the download fails.
"""
if not url:
raise BenchmarkError(
5,
f"no default download URL ({VERSIONS_ERROR}). Pass --benchmark-url "
f"{BINARIES_BUCKET}/<release>/android_arm64/benchmark_model, or "
"--benchmark-bin and --dispatch-lib.",
)
tag = re.sub(r"[^A-Za-z0-9._-]", "_", url.split("/binaries/", 1)[-1])
cached = CACHE_DIR / tag
if cached.is_file() and not refresh:
return cached, (
f"cached download of {url} ({_fetch_text(_read_download_meta(cached))})"
)
if dry_run:
print(f" [dry-run] would download {url} -> {cached}")
return cached, f"would download from {url}"
cached.parent.mkdir(parents=True, exist_ok=True)
print(f"Downloading {url} ...")
part = cached.with_suffix(cached.suffix + ".part")
try:
with (
urllib.request.urlopen(url, timeout=120) as resp,
open(part, "wb") as f,
):
shutil.copyfileobj(resp, f)
headers = resp.headers
except (urllib.error.URLError, OSError) as e:
raise BenchmarkError(
5,
f"download failed ({e}). Download it manually from {url} and pass "
f"{manual_flag}, or pick another release directory with "
"--benchmark-url (.../binaries/<release>/android_arm64/...).",
) from e
part.replace(cached)
cached.chmod(0o755)
hashes = _gcs_hashes(headers)
meta = {
"url": url,
"fetched_at": (
datetime.datetime.now(datetime.timezone.utc).strftime(
"%Y-%m-%dT%H:%M:%SZ"
)
),
"size_bytes": cached.stat().st_size,
"sha256": _sha256(cached),
"gcs_generation": headers.get("x-goog-generation"),
"gcs_md5": hashes.get("md5"),
"gcs_crc32c": hashes.get("crc32c"),
}
try:
_meta_path(cached).write_text(
json.dumps(meta, indent=2) + "\n", encoding="utf-8"
)
except OSError:
pass # the next run then reports "fetch date not recorded"
return cached, f"downloaded from {url} ({_fetch_text(meta)})"
def resolve_dispatch_lib(
spec: str | None,
scratch: pathlib.Path,
url: str | None,
refresh: bool = False,
dry_run: bool = False,
) -> tuple[pathlib.Path, str]:
"""Returns (local path, provenance) for libLiteRtDispatch_GoogleTensor.so.
Order: --dispatch-lib, then $LITERT_GOOGLE_TENSOR_DISPATCH_LIB, then a cached
download of ``url`` (the dispatch library next to benchmark_model).
Args:
spec: The --dispatch-lib value (the .so, a directory, or a .zip/.aar that
contains it), or None.
scratch: Temporary local directory to extract a .zip/.aar member into.
url: Download URL for when no path is given, or None.
refresh: Whether to download again even if a cached copy exists.
dry_run: Whether to only print what would be downloaded.
Raises:
BenchmarkError: If the given path does not provide the library, or the
download fails.
"""
spec = spec or os.environ.get(DISPATCH_LIB_ENV)
if not spec:
return _cached_download(url, refresh, dry_run, "--dispatch-lib")
path = pathlib.Path(spec).expanduser()
if path.is_dir():
hits = sorted(path.rglob(DISPATCH_LIB_NAME))
if hits:
hit = _prefer_arm64(hits)
return hit, f"user-provided: {hit}"
raise BenchmarkError(
5, f"{DISPATCH_LIB_NAME} not found under {path}.\n" + DISPATCH_LIB_HELP
)
if path.is_file() and zipfile.is_zipfile(path):
with zipfile.ZipFile(path) as zf:
members = [
m
for m in zf.namelist()
if m.endswith("/" + DISPATCH_LIB_NAME) or m == DISPATCH_LIB_NAME
]
if not members:
raise BenchmarkError(
5, f"{DISPATCH_LIB_NAME} not inside {path}.\n" + DISPATCH_LIB_HELP
)
member = _prefer_arm64(members)
dest = scratch / DISPATCH_LIB_NAME
with zf.open(str(member)) as src, open(dest, "wb") as out:
shutil.copyfileobj(src, out)
print(f"Extracted {member} from {path.name}")
return dest, f"extracted {member} from {path}"
if path.is_file():
with open(path, "rb") as f:
is_elf = f.read(4) == b"\x7fELF"
if is_elf:
# Any ELF shared object is accepted whatever its local file name (e.g. a
# renamed download); it is pushed to the device as DISPATCH_LIB_NAME.
if path.name != DISPATCH_LIB_NAME:
print(f"Note: using {path.name} as {DISPATCH_LIB_NAME}.")
return path, f"user-provided: {path}"
raise BenchmarkError(
5,
f"--dispatch-lib {spec} is not an ELF shared library, "
"a directory, a .zip or an .aar.\n"
+ DISPATCH_LIB_HELP,
)
def _prefer_arm64(candidates):
for c in candidates:
if "arm64-v8a" in str(c) or "arm64" in str(c):
return c
return candidates[0]
def resolve_benchmark_bin(
spec: str | None, url: str | None, refresh: bool, dry_run: bool = False
) -> tuple[pathlib.Path, str]:
"""Returns (local path, provenance string) for the android_arm64 binary."""
if spec:
path = pathlib.Path(spec).expanduser()
if not path.is_file():
raise BenchmarkError(5, f"--benchmark-bin {path} does not exist.")
return path, f"user-provided: {path}"
return _cached_download(url, refresh, dry_run, "--benchmark-bin")
# --------------------------------------------------------------------------
# Output parsing
# --------------------------------------------------------------------------
_PATTERNS = {
"signature": r"Signature name:[ \t]+(.+)",
"init_ms": r"Model initialization:\s+([\d.]+) ms",
"warmup_first_ms": r"Warmup \(first\):\s+([\d.]+) ms",
"warmup_avg_ms": r"Warmup \(avg\):\s+([\d.]+) ms \((\d+) runs\)",
"inference_avg_ms": r"Inference \(avg\):\s+([\d.]+) ms \((\d+) runs\)",
"inference_min_ms": r"Inference \(min\):\s+([\d.]+) ms",
"inference_max_ms": r"Inference \(max\):\s+([\d.]+) ms",
"inference_std_ms": r"Inference \(std\):\s+([\d.]+)",
"throughput_mb_s": r"Throughput:\s+([\d.]+) MB/s",
"init_footprint_mb": r"Init footprint:\s+([\d.]+) MB",
"overall_footprint_mb": r"Overall footprint:\s+([\d.]+) MB",
"peak_memory_mb": r"Peak memory:\s+([\d.]+) MB",
}
# "Replacing 1 out of 1 node(s) with delegate (DispatchDelegate) node,
# yielding 1 partitions for subgraph 0 (main)."
_DELEGATION_RE = re.compile(
r"Replacing (\d+) out of (\d+) node\(s\) with delegate \((\w+)\)"
)
# Older binaries print the upstream TFLite one-liner in microseconds.
_LEGACY_TIMINGS = re.compile(
r"Inference timings in us: Init: ([\d.e+]+), First inference: ([\d.e+]+), "
r"Warmup \(avg\): ([\d.e+]+), Inference \(avg\): ([\d.e+]+)"
)
_LEGACY_PEAK = re.compile(
r"Overall peak memory footprint \(MB\) via periodic monitoring: ([\d.]+)"
)
# Per-phase stats lines (microseconds), one for warmup and one for the measured
# phase; the only place benchmark_model reports percentiles:
# "INFO: count=200 first=12110 curr=16718 min=10557 max=17736 avg=15390.9
# std=2115 p5=11716 median=16428 p95=17481"
_PHASE_STATS = re.compile(
r"count=(\d+) first=[\d.]+ curr=[\d.]+ min=[\d.]+ max=[\d.]+ avg=[\d.]+ "
r"std=[\d.]+ p5=([\d.]+) median=([\d.]+) p95=([\d.]+)"
)
def parse_benchmark_log(text: str) -> dict[str, Any]:
"""Parses benchmark_model output (current or legacy format) into a dict.
Args:
text: Output of one benchmark_model run.
Returns:
The values found (times in ms, memory in MB): the _PATTERNS keys,
warmup_runs, measured_runs, delegated_nodes, total_nodes, delegate,
inference_p5_ms, inference_p50_ms, inference_p95_ms and profile_summary.
Keys whose line is not in the log are left out.
"""
res = {}
for key, pat in _PATTERNS.items():
m = re.search(pat, text)
if not m:
continue
if key == "signature":
res[key] = m.group(1).strip()
else:
res[key] = float(m.group(1))
if key == "warmup_avg_ms":
res["warmup_runs"] = int(m.group(2))
if key == "inference_avg_ms":
res["measured_runs"] = int(m.group(2))
m = _DELEGATION_RE.search(text)
if m:
res["delegated_nodes"] = int(m.group(1))
res["total_nodes"] = int(m.group(2))
res["delegate"] = m.group(3)
# Percentiles of the measured phase: the stats line whose count matches the
# measured-run count (else the last stats line before the results box).
results_at = text.find("BENCHMARK RESULTS")
phases = [
m
for m in _PHASE_STATS.finditer(text)
if results_at == -1 or m.start() < results_at
]
if phases:
measured = [
m for m in phases if int(m.group(1)) == res.get("measured_runs", -1)
]
m = (measured or phases)[-1]
res["inference_p5_ms"] = float(m.group(2)) / 1000.0
res["inference_p50_ms"] = float(m.group(3)) / 1000.0
res["inference_p95_ms"] = float(m.group(4)) / 1000.0
if "inference_avg_ms" not in res:
m = _LEGACY_TIMINGS.search(text)
if m:
init, first, warm, inf = (float(x) / 1000.0 for x in m.groups())
res.update(
init_ms=init,
warmup_first_ms=first,
warmup_avg_ms=warm,
inference_avg_ms=inf,
)
m = _LEGACY_PEAK.search(text)
if m:
res["peak_memory_mb"] = float(m.group(1))
# Op profile summary (when --use_profiler) is printed after the results box,
# i.e. after the first all-'=' rule that follows "BENCHMARK RESULTS". Without
# the profiler that tail only holds teardown log lines, which are not a
# profile, so require one of the profiler's section headings.
header = text.find("BENCHMARK RESULTS")
if header != -1:
closing = re.compile(r"^[^\n=]*={30,}[^\n=]*$", re.M).search(text, header)
if closing:
tail = text[closing.end() :].strip()
if tail and re.search(
r"Profiling Info|Operator-wise|node type", tail, re.I
):
res["profile_summary"] = tail
return res
# benchmark_model ends a failed run with "Benchmarking failed." and a non-zero
# exit code. The other markers also catch a crash that an old adb (one that
# does not forward the exit code) reports as exit 0.
_FAILURE_MARKERS = (
"Benchmarking failed",
"Segmentation fault",
"Aborted",
"Fatal signal",
"CANNOT LINK EXECUTABLE",
)
def output_unrecognized(code: int, text: str, parsed: dict[str, Any]) -> bool:
"""True if benchmark_model exited 0 but printed no result this script parses.
That points at a changed output format (a binary newer or older than
_PATTERNS), not at a failed run, so retrying without the profiler would
only run the whole benchmark again for the same result.
Args:
code: Exit code of the benchmark_model run.
text: Output of the run.
parsed: parse_benchmark_log() result for ``text``.
Returns:
True if ``code`` is 0, ``parsed`` has no inference average and ``text``
has none of the _FAILURE_MARKERS.
"""
return (
code == 0
and "inference_avg_ms" not in parsed
and not any(marker in text for marker in _FAILURE_MARKERS)
)
def unrecognized_output_error(
label: str, text: str, bench_src: str, log_path: pathlib.Path, retried: bool
) -> str:
"""Returns the error for a run that exited 0 but printed no parsable result.
Args:
label: Name of the run, e.g. ``NPU``.
text: Output of the run.
bench_src: Provenance of the benchmark_model binary.
log_path: Local file with the run's full log.
retried: Whether the run was already a retry without the profiler.
"""
what = (
"printed nothing"
if not text.strip()
else "printed no results in the format this script parses"
)
tail = "\n".join(text.splitlines()[-20:])
if retried:
retry_note = ""
else:
retry_note = (
" No profiler retry was attempted (it cannot fix a format change)."
)
return (
f"{label} benchmark: benchmark_model exited 0 but {what}. The "
"binary is probably newer or older than the parser (_PATTERNS in "
f"benchmark_on_device.py). Binary: {bench_src}. Fix: run with the "
"default release (versions.json) or pin a release whose output "
f"parses with --benchmark-url {BINARIES_BUCKET}/<release>/"
"android_arm64/benchmark_model, or update _PATTERNS for the new "
"format."
+ retry_note
+ (f"\nLast lines:\n{tail}" if tail else "")
+ f"\nFull log: {log_path}"
)
def analyze_tile_pass(code: int, text: str, report: str) -> dict[str, object]:
"""TPU tile time per inference from the tile pass, or why there is none.
``report`` is the hook's dump file (empty if missing); the same numbers are
also in the log, which is the fallback. The per-inference value is
``Total TPU tile time / (warmup + measured runs)`` of this pass. The hook's
own count is only a consistency check: it was (1 + D) x runs (D = dispatch
nodes), i.e. 2x for a normal compiled model, with the 2.3.0 binaries
(observed 2026-10-09), and D x runs with the 2.3.1 binaries re-uploaded on
2026-10-23 (observed 2026-10-26).
Args:
code: Exit code from the tile-time benchmark pass.
text: Captured stdout/stderr log from the tile-time pass.
report: Contents of the hook's tile-time report file, or empty string.
Returns:
Dictionary describing the tile-time measurement status and metrics.
"""
run = parse_benchmark_log(text)
res: dict[str, object] = {
"status": "failed",
"reason": None,
"hook_registered": _HOOKS_REGISTERED in text,
"warmup_runs": run.get("warmup_runs"),
"measured_runs": run.get("measured_runs"),
"dispatch_nodes": run.get("delegated_nodes"),
# Not reported as latency: the hook adds ~3% per inference (measured).
"pass_inference_avg_ms": run.get("inference_avg_ms"),
}
if code == 124:
res["reason"] = "the tile-time pass timed out (see tile_time.log)"
return res
if code != 0 or "inference_avg_ms" not in run:
res["reason"] = (
f"the tile-time pass failed (exit {code}); see tile_time.log"
)
return res
if not res["hook_registered"]:
res["status"] = "unavailable"
if _HOOKS_NULL in text:
res["reason"] = (
"the dispatch library returned no telemetry hook ('Accelerator "
"returned null hooks.'); builds from the LiteRT GitHub source have "
"the hooks compiled out, the Google-built bucket binaries have them"
)
else:
res["reason"] = "no 'registered vendor hooks' line in tile_time.log"
return res
source = "file"
total, count = _TILE_TOTAL_RE.search(report), _TILE_COUNT_RE.search(report)
if not (total and count):
source = "log"
total, count = _TILE_TOTAL_RE.search(text), _TILE_COUNT_RE.search(text)
if not (total and count):
res["status"] = "no_report"
res["reason"] = "the hook wrote no tile report (neither file nor log lines)"
return res
runs = (res["warmup_runs"] or 0) + (res["measured_runs"] or 0)
total_us, hook_count = int(total.group(1)), int(count.group(1))
res.update(source=source, runs=runs, total_us=total_us, hook_count=hook_count)
nodes = res["dispatch_nodes"]
meaning = None
if runs and hook_count % runs == 0:
k = hook_count // runs
res["count_ratio"] = k
if nodes and k == nodes + 1:
meaning = (
f"{k} calls per run ({nodes} dispatch invoke"
f"{'s' if nodes != 1 else ''} + 1 extra call from the LiteRT "
"runtime: the known double count, corrected)"
)
elif nodes and k == nodes:
meaning = (
f"{k} call{'s' if k != 1 else ''} per run, one per dispatch invoke"
)
elif k == 1:
meaning = "1 call per run"
elif not nodes:
meaning = f"{k} calls per run (dispatch node count not in the log)"
elif runs:
res["count_ratio"] = round(hook_count / runs, 3)
if meaning is None:
res["status"] = "inconsistent"
res["reason"] = (
f"the hook counted {hook_count} calls for {runs} runs, which matches "
"no known pattern (1 + D, D or 1 per run; D = dispatch nodes), so no "
"per-inference value is reported"
)
return res
res.update(
status="ok",
count_meaning=meaning,
per_inference_ms=total_us / runs / 1000.0,
)
return res
def tile_time_text(t: dict[str, object]) -> str:
"""Text of the **TPU tile time:** header line."""
status = t["status"]
if status == "skipped":
return "not measured (--no-tile-time)"
if status == "ok":
return (
f"from the dispatch library's hook ({HOOK_ENV}) in a separate hooked "
f"pass of {t['runs']} runs ({t['warmup_runs']} warmup + "
f"{t['measured_runs']} measured; warmups included): "
f"{t['total_us'] / 1000:.2f} ms in total; the hook counted "
f"{t['hook_count']} = {t['count_meaning']}; per inference = total / "
f"{t['runs']} runs"
)
if t.get("total_us") is not None:
return (
f"{status} - {t['total_us'] / 1000:.2f} ms in total over "
f"{t['runs']} runs, but {t['reason']}"
)
return f"{status.replace('_', ' ')} - {t['reason']}"
def analyze_power_pass(code: int, text: str, report: str) -> dict[str, object]:
"""TPU energy per inference from the hooked pass, or why there is none.
``report`` is the power hook's dump file (empty if missing); the same numbers
are also in the log, which is the fallback. The hook's ``Total Energy`` is
the TPU rail's energy from the start of the first dispatch invoke to the
model's teardown, so it includes the TPU's idle gaps between inferences.
The per-inference value is that total / (warmup + measured runs) of the
pass, like the tile time. The hook's own count is a check: one call per
dispatch invoke with the 2.3.1 binaries re-uploaded on 2026-10-23 (observed
2026-10-26); 1 + D per run is the old power hook, whose totals miss most of
the energy, so it gets no value.
Args:
code: Exit code of the hooked benchmark pass.
text: Captured stdout/stderr log of the hooked pass.
report: Contents of the power hook's report file, or empty string.
Returns:
Dictionary describing the energy measurement status and values.
"""
run = parse_benchmark_log(text)
res: dict[str, object] = {
"status": "failed",
"reason": None,
"hook_registered": _HOOKS_REGISTERED in text,
"warmup_runs": run.get("warmup_runs"),
"measured_runs": run.get("measured_runs"),
"dispatch_nodes": run.get("delegated_nodes"),
}
if code == 124:
res["reason"] = "the hooked pass timed out (see tile_time.log)"
return res
if code != 0 or "inference_avg_ms" not in run:
res["reason"] = f"the hooked pass failed (exit {code}); see tile_time.log"
return res
if not res["hook_registered"]:
res["status"] = "unavailable"
if _HOOKS_NULL in text:
res["reason"] = (
"the dispatch library returned no telemetry hook ('Accelerator "
"returned null hooks.')"
)
else:
res["reason"] = "no 'registered vendor hooks' line in tile_time.log"
return res
source = "file"
total, count = _POWER_TOTAL_RE.search(report), _POWER_COUNT_RE.search(report)
if not (total and count):
source = "log"
total, count = _POWER_TOTAL_RE.search(text), _POWER_COUNT_RE.search(text)
if not (total and count):
failure = _POWER_FAILURE_RE.search(text)
if failure:
res["status"] = "unavailable"
res["reason"] = (
"the power hook could not read the TPU energy counter: "
f"'{failure.group(0).strip()[:200]}'"
)
else:
res["status"] = "no_report"
res["reason"] = (
"the power hook wrote no report (neither file nor log lines)"
)
return res
runs = (res["warmup_runs"] or 0) + (res["measured_runs"] or 0)
total_uj, hook_count = int(total.group(1)), int(count.group(1))
res.update(source=source, runs=runs, total_uj=total_uj, hook_count=hook_count)
nodes = res["dispatch_nodes"]
meaning = None
if runs and hook_count % runs == 0:
k = hook_count // runs
res["count_ratio"] = k
if nodes and k == nodes:
meaning = (
f"{k} call{'s' if k != 1 else ''} per run, one per dispatch invoke"
)
elif nodes and k == nodes + 1:
res["status"] = "unreliable"
res["reason"] = (
f"the hook counted {hook_count} = {k} calls per run, the pattern of "
"the old power hook, which reads the energy counter around every "
"call and misses most of the energy, so no value is reported"
)
return res
elif k == 1:
meaning = "1 call per run"
elif runs:
res["count_ratio"] = round(hook_count / runs, 3)
if meaning is None:
res["status"] = "inconsistent"
res["reason"] = (
f"the hook counted {hook_count} calls for {runs} runs, which matches "
"no known pattern (D or 1 per run; D = dispatch nodes), so no "
"per-inference value is reported"
)
return res
res.update(
status="ok",
count_meaning=meaning,
per_inference_mj=total_uj / runs / 1000.0,
)
return res
def power_text(p: dict[str, object]) -> str:
"""Text of the **TPU energy:** header line."""
status = p["status"]
if status == "skipped":
return "not measured (--no-power)"
if status == "ok":
return (
f"from the dispatch library's power hook ({HOOK_ENV}) in the hooked "
f"pass of {p['runs']} runs ({p['warmup_runs']} warmup + "
f"{p['measured_runs']} measured; warmups included): "
f"{p['total_uj'] / 1000:.2f} mJ on the TPU rail from the first "
"inference to the model's teardown, idle gaps included; the hook "
f"counted {p['hook_count']} = {p['count_meaning']}; per inference = "
f"total / {p['runs']} runs"
)
if p.get("total_uj") is not None:
return (
f"{status} - {p['total_uj'] / 1000:.2f} mJ in total over "
f"{p['runs']} runs, but {p['reason']}"
)
return f"{status.replace('_', ' ')} - {p['reason']}"
# --------------------------------------------------------------------------
# Log check: WARNING/ERROR-level lines the reader should look at
# --------------------------------------------------------------------------
# benchmark_model and the LiteRT runtime log as "WARNING: [file:line] ..." /
# "ERROR: ..."; the Google Tensor driver adds abseil-style "E0000 12:34:56 ..."
# lines. Lines matching _BENIGN_LOG_LINES appear in every successful strict run
# on a Pixel (documented in references/benchmark-flags.md) and are only
# counted; everything else is listed verbatim so nobody has to grep the log.
_ATTENTION_RE = re.compile(
r"\b(?:WARNING|ERROR|FATAL|FAILED|[Ff]ailed|INTERNAL)\b"
r"|^[EWF]\d{4} \d{2}:\d{2}"
)
_BENIGN_LOG_LINES = (
re.compile(
r"Compiler plugin path is provided in the environment, but the "
r"model is pre-compiled"
),
re.compile(r"dispatch API returned contradictory buffer requirements"),
)
_MAX_UNEXPECTED_LINES = 8 # shown in the report
_MAX_STORED_UNEXPECTED = 50 # kept in results.json
def check_log(text: str) -> dict[str, Any]:
"""Counts known-benign warning lines and collects unexpected ones.
Unexpected lines are de-duplicated on a digit-normalised key (driver errors
repeat with different timestamps); the first verbatim occurrence is kept
with its repeat count.
Args:
text: Output of one benchmark_model run.
Returns:
Dict with the ``benign_lines`` count, the ``unexpected_total`` count
(repeats included) and ``unexpected_lines``: up to _MAX_STORED_UNEXPECTED
distinct lines, each suffixed with (xN) if it occurred N > 1 times.
"""
benign = 0
unexpected: dict[str, list[Any]] = {}
for line in text.splitlines():
line = line.strip()
if not line or not _ATTENTION_RE.search(line):
continue
if any(p.search(line) for p in _BENIGN_LOG_LINES):
benign += 1
continue
key = re.sub(r"\d+", "N", line)
if key in unexpected:
unexpected[key][1] += 1
else:
unexpected[key] = [line, 1]
lines = [
f"{line} (x{n})" if n > 1 else line for line, n in unexpected.values()
]
return {
"benign_lines": benign,
"unexpected_total": sum(n for _, n in unexpected.values()),
"unexpected_lines": lines[:_MAX_STORED_UNEXPECTED],
}
def log_check_text(name: str, chk: dict[str, Any] | None) -> str:
if chk is None:
return f"{name}: not run"
n = chk["unexpected_total"]
return (
f"{name}: {n} unexpected WARNING/ERROR line{'s' if n != 1 else ''} "
f"({chk['benign_lines']} known-benign)"
)
def unexpected_lines_md(checks: dict[str, dict[str, Any] | None]) -> str:
"""Markdown section listing unexpected log lines, or '' if none."""
items = []
for name, chk in checks.items():
lines = (chk or {}).get("unexpected_lines", [])
for line in lines[:_MAX_UNEXPECTED_LINES]:
items.append(f"- {name}: `{line.replace('`', chr(39))}`")
if len(lines) > _MAX_UNEXPECTED_LINES:
items.append(
f"- {name}: ... {len(lines) - _MAX_UNEXPECTED_LINES} more "
"distinct lines (see the log file)"
)
if not items:
return ""
return (
"\n\n**Unexpected log lines** (not in the benign list of "
"references/benchmark-flags.md; judge them before reporting):\n"
+ "\n".join(items)
)
# --------------------------------------------------------------------------
# Versions: the LiteRT that compiled the model vs the release that runs it
# --------------------------------------------------------------------------
def runtime_release(user_provided: bool, url: str | None) -> str:
"""Bucket release of a binary ('latest', 'X.Y.Z') or how it was given."""
if user_provided:
return "user-provided"
m = re.search(r"/binaries/([^/]+)/android_arm64/", url or "")
return m.group(1) if m else "custom URL"
def _source_text(release: str) -> str:
return {
"user-provided": "user-provided files",
"custom URL": "a custom URL",
}.get(release, f"bucket release '{release}'")
def versions_summary(
sidecar: dict[str, Any] | None, bench_release: str, dispatch_release: str
) -> tuple[str, dict[str, Any]]:
"""Text of the **Versions:** header line and the results.json entry.
Compares the ai-edge-litert version recorded in the compile sidecar with
the bucket release the runtime binaries came from. Rolling releases
('latest', 'nightly') and local files carry no version number, so the line
says why the two cannot be compared instead of guessing.
Args:
sidecar: Contents of the model's compile sidecar, or None if it has none.
bench_release: runtime_release() of the benchmark_model binary.
dispatch_release: runtime_release() of the dispatch library.
Returns:
(Versions line text, ``versions`` entry for results.json).
"""
packages = (sidecar or {}).get("packages") or {}
compiled = packages.get("ai-edge-litert") or packages.get(
"ai-edge-litert-nightly"
)
sdk = packages.get("ai-edge-litert-sdk-google-tensor") or packages.get(
"ai-edge-litert-sdk-google-tensor-nightly"
)
if compiled:
compile_text = f"compiled with ai-edge-litert {compiled}"
if sdk and sdk != compiled:
compile_text += f" but SDK package {sdk} (DIFFERENT)"
elif sidecar is None:
compile_text = "compile version unknown (no compile sidecar)"
else:
compile_text = "compile version not recorded in the sidecar"
if bench_release == dispatch_release:
runtime_text = f"runtime binaries from {_source_text(bench_release)}"
else:
runtime_text = (
f"benchmark_model from {_source_text(bench_release)}, "
f"dispatch library from {_source_text(dispatch_release)}"
)
if bench_release != dispatch_release:
match = "mixed_runtime"
verdict = "the two runtime binaries come from different sources"
elif not compiled:
match, verdict = "unknown", "cannot compare"
elif not re.fullmatch(r"\d+(\.\d+)+", bench_release):
match = "unverified"
reason = {
"user-provided": "local files carry no version",
"custom URL": "the URL names no release",
}.get(bench_release, f"'{bench_release}' is a rolling build")
verdict = f"not comparable ({reason})"
elif compiled == bench_release:
match, verdict = "same", "same release"
else:
match, verdict = "different", "DIFFERENT releases"
if compiled == VERSIONS.get(
"pip_release"
) and bench_release == VERSIONS.get("binaries_release"):
verdict += " (the pair verified in versions.json)"
entry = {
"compiled_with": compiled,
"runtime_release": {
"benchmark_model": bench_release,
"dispatch_library": dispatch_release,
},
"pinned": {
"pip_release": VERSIONS.get("pip_release"),
"binaries_release": VERSIONS.get("binaries_release"),
},
"match": match,
}
return f"{compile_text}; {runtime_text} - {verdict}", entry
# --------------------------------------------------------------------------
# Main flow
# --------------------------------------------------------------------------
def parse_args(argv=None) -> argparse.Namespace:
"""Parses command-line flags from ``argv`` (default: ``sys.argv[1:]``)."""
p = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
p.add_argument(
"--model",
required=True,
help=(
"Google Tensor AOT-compiled .tflite (from "
"compile_model.py or any other Google Tensor compile; "
"check with check_compiled.py)."
),
)
p.add_argument(
"--dispatch-lib",
help=(
f"{DISPATCH_LIB_NAME}, or a directory/.zip/.aar containing "
f"it (default: ${DISPATCH_LIB_ENV}, else a cached download "
"of --dispatch-url)."
),
)
p.add_argument(
"--benchmark-bin",
help=(
"Local android_arm64 benchmark_model binary. Default: "
"download --benchmark-url once and cache it."
),
)
url_default_note = (
"binaries_release in the skill's versions.json"
if DEFAULT_BENCHMARK_URL
else f"unavailable: {VERSIONS_ERROR}".replace("%", "%%")
)
p.add_argument(
"--benchmark-url",
default=DEFAULT_BENCHMARK_URL,
help=(
"Where to download benchmark_model from (default: "
f"%(default)s; {url_default_note}). Use .../binaries/"
"<release>/android_arm64/benchmark_model to pin a "
"release ('latest', 'nightly', 'X.Y.Z', ...)."
),
)
p.add_argument(
"--dispatch-url",
help=(
f"Where to download {DISPATCH_LIB_NAME} from (default: "
"same directory as --benchmark-url)."
),
)
p.add_argument(
"--refresh-binary",
action="store_true",
help=(
"Re-download the benchmark binary and dispatch library "
"even if cached."
),
)
p.add_argument("--serial", help="adb serial (required if >1 device).")
p.add_argument(
"--cpu-baseline",
metavar="ORIGINAL_TFLITE",
help="Also benchmark this UNCOMPILED model on the CPU.",
)
p.add_argument(
"--cpu-num-threads",
type=int,
help="CPU threads for the baseline (default: runtime choice).",
)
p.add_argument("--num-runs", type=int, default=50)
p.add_argument("--warmup-runs", type=int, default=5)
p.add_argument(
"--signature",
help=(
"Signature key to run (multi-signature "
"models); passed as --signature_to_run_for."
),
)
p.add_argument(
"--performance-mode",
choices=PERFORMANCE_MODES,
help="--google_tensor_performance_mode (benchmark default: burst).",
)
p.add_argument(
"--no-profiler",
action="store_true",
help="Disable --use_profiler=true (op-level timing).",
)
p.add_argument(
"--no-peak-memory",
action="store_true",
help="Disable --report_peak_memory_footprint=true.",
)
p.add_argument(
"--no-tile-time",
action="store_true",
help=(
"Do not read TPU tile time from the dispatch library's hook "
f"({HOOK_ENV}). With --no-power too, the extra hooked NPU pass is "
"skipped."
),
)
p.add_argument(
"--no-power",
action="store_true",
help=(
"Do not read TPU energy from the dispatch library's power hook "
"(measured in the same hooked NPU pass as the TPU tile time)."
),
)
p.add_argument(
"--extra-arg",
action="append",
default=[],
help=(
"Extra benchmark_model flag, e.g. --extra-arg=--min_secs=5 "
"(repeatable; applied to the NPU run and the hooked pass)."
),
)
p.add_argument(
"--device-dir",
default=DEFAULT_DEVICE_DIR,
help=(
"Base scratch directory on the phone (default: "
"%(default)s). Each run pushes into a fresh "
"<base>/run-<timestamp>-<pid>/ subdirectory and deletes "
"only that, so files already in the base directory are "
"never overwritten or removed."
),
)
p.add_argument(
"--keep-device-files",
action="store_true",
help="Do not delete the per-run device directory afterwards.",
)
p.add_argument(
"--allow-mismatch",
action="store_true",
help="Run even if the model's SoC stamp != device SoC.",
)
p.add_argument(
"--allow-cpu-fallback",
action="store_true",
help=(
"Drop --use_cpu=false/--require_full_delegation=true so "
"partially compiled models run with CPU fallback "
"(numbers then mix NPU and CPU time)."
),
)
p.add_argument(
"--timeout",
type=int,
default=900,
help="Seconds allowed per benchmark run (default: 900).",
)
p.add_argument(
"--output-dir",
help=(
"Where to write logs + results.json (default: "
"./litert_benchmark_results/<timestamp>)."
),
)
p.add_argument(
"--dry-run",
action="store_true",
help=(
"Validate inputs and print the adb commands; do not touch the device."
),
)
return p.parse_args(argv)
def build_npu_args(args, remote_model: str, device_dir: str) -> list[str]:
"""Returns the benchmark_model flags for the NPU run.
Args:
args: Parsed command-line arguments.
remote_model: Device path of the compiled model.
device_dir: Device directory that holds the dispatch library.
"""
flags = [
f"--graph={shlex.quote(remote_model)}",
"--use_npu=true",
]
if not args.allow_cpu_fallback:
# Strict mode: abort instead of silently running ops on the CPU.
flags += ["--use_cpu=false", "--require_full_delegation=true"]
flags += [
f"--dispatch_library_path={shlex.quote(device_dir)}",
f"--num_runs={args.num_runs}",
f"--warmup_runs={args.warmup_runs}",
]
if not args.no_peak_memory:
flags.append("--report_peak_memory_footprint=true")
if not args.no_profiler:
flags.append("--use_profiler=true")
if args.signature:
flags.append(f"--signature_to_run_for={shlex.quote(args.signature)}")
if args.performance_mode:
flags.append(f"--google_tensor_performance_mode={args.performance_mode}")
flags.extend(args.extra_arg)
return flags
def build_cpu_args(args, remote_model: str) -> list[str]:
"""Returns the benchmark_model flags for the CPU baseline run.
Args:
args: Parsed command-line arguments.
remote_model: Device path of the original (uncompiled) model.
"""
flags = [
f"--graph={shlex.quote(remote_model)}",
"--use_cpu=true",
f"--num_runs={args.num_runs}",
f"--warmup_runs={args.warmup_runs}",
]
if not args.no_peak_memory:
flags.append("--report_peak_memory_footprint=true")
if not args.no_profiler:
flags.append("--use_profiler=true")
if args.signature:
flags.append(f"--signature_to_run_for={shlex.quote(args.signature)}")
if args.cpu_num_threads:
flags.append(f"--num_threads={args.cpu_num_threads}")
return flags
def build_tile_args(npu_flags: list[str]) -> list[str]:
"""Returns flags for the hooked pass (NPU flags minus profiler/memory).
Args:
npu_flags: Command-line flags used for the main NPU benchmark pass.
Returns:
Filtered list of command-line flags for the hooked pass (TPU tile time
and TPU energy).
"""
drop = {"--use_profiler=true", "--report_peak_memory_footprint=true"}
return [f for f in npu_flags if f not in drop]
def run_benchmark(
adb: Adb,
remote_bin: str,
flags: list[str],
log_path: pathlib.Path,
timeout: int,
label: str,
env: str = "",
) -> tuple[int, str]:
"""Runs benchmark_model on the device and writes its output to ``log_path``.
Args:
adb: Device connection; in dry-run mode nothing is run.
remote_bin: Device path of the benchmark_model binary.
flags: benchmark_model flags, already shell-quoted where needed.
log_path: Local file that receives the run's output.
timeout: Seconds allowed for the run before adb is killed.
label: Tag printed before the command, e.g. ``NPU``.
env: Optional ``NAME=value`` prefix for the device shell command.
Returns:
(exit code, output text); (124, a timeout message) if the run timed out,
(0, "") in dry-run mode.
"""
cmd = (f"{env} " if env else "") + f"{shlex.quote(remote_bin)} "
cmd += " ".join(flags)
print(f"\n[{label}] adb shell {cmd}")
if adb.dry_run:
return 0, ""
try:
proc = adb.shell(cmd, timeout=timeout, check=False)
except subprocess.TimeoutExpired:
log_path.write_text(f"TIMEOUT after {timeout}s\n")
return 124, f"timed out after {timeout}s"
text = proc.stdout or ""
log_path.write_text(text)
return proc.returncode, text
def read_device_file(adb: Adb, path: str) -> str:
"""Contents of a small file on the phone, or '' if it cannot be read."""
try:
return (
adb.shell(f"cat {shlex.quote(path)}", check=False, timeout=60).stdout
or ""
)
except subprocess.TimeoutExpired:
return ""
def fmt(v, digits=2):
return "-" if v is None else f"{v:.{digits}f}"
def markdown_table(
npu: dict[str, object],
cpu: dict[str, object] | None,
npu_name: str,
cpu_name: str | None,
soc: str,
npu_only_rows: list[tuple[str, str]] | None = None,
) -> str:
"""Formats the NPU (and CPU baseline) results as a Markdown table.
Args:
npu: Parsed results of the NPU run (parse_benchmark_log).
cpu: Parsed results of the CPU baseline run, or None for no CPU column.
npu_name: File name of the compiled model.
cpu_name: File name of the CPU baseline model, or None.
soc: SoC label for the NPU column header.
npu_only_rows: Extra (metric, value) rows that have no CPU value.
Returns:
The table, followed by an NPU speed-up line if both runs report an
average latency.
"""
cols = [f"NPU ({soc})"] + (["CPU baseline"] if cpu is not None else [])
rows = [
("Model file", [npu_name] + ([cpu_name] if cpu is not None else [])),
(
"Model init (ms)",
[fmt(npu.get("init_ms")), fmt((cpu or {}).get("init_ms"))],
),
(
"Warmup first (ms)",
[
fmt(npu.get("warmup_first_ms")),
fmt((cpu or {}).get("warmup_first_ms")),
],
),
(
"Warmup avg (ms)",
[
fmt(npu.get("warmup_avg_ms")),
fmt((cpu or {}).get("warmup_avg_ms")),
],
),
(
"Inference avg (ms)",
[
fmt(npu.get("inference_avg_ms")),
fmt((cpu or {}).get("inference_avg_ms")),
],
),
(
"Inference min / max (ms)",
[
(
f"{fmt(npu.get('inference_min_ms'))} /"
f" {fmt(npu.get('inference_max_ms'))}"
),
(
f"{fmt((cpu or {}).get('inference_min_ms'))} / "
f"{fmt((cpu or {}).get('inference_max_ms'))}"
),
],
),
(
"Inference std (ms)",
[
fmt(npu.get("inference_std_ms")),
fmt((cpu or {}).get("inference_std_ms")),
],
),
]
if "inference_p50_ms" in npu or "inference_p50_ms" in (cpu or {}):
def _pct(d):
return (
f"{fmt(d.get('inference_p5_ms'), 3)} / "
f"{fmt(d.get('inference_p50_ms'), 3)} / "
f"{fmt(d.get('inference_p95_ms'), 3)}"
)
rows.append(("Inference p5 / p50 / p95 (ms)", [_pct(npu), _pct(cpu or {})]))
rows += [(name, [value, "-"]) for name, value in npu_only_rows or []]
rows += [
(
"Peak memory (MB)",
[
fmt(npu.get("peak_memory_mb")),
fmt((cpu or {}).get("peak_memory_mb")),
],
),
(
"Runs (warmup / measured)",
[
(
f"{npu.get('warmup_runs', '-')} /"
f" {npu.get('measured_runs', '-')}"
),
(
f"{(cpu or {}).get('warmup_runs', '-')} / "
f"{(cpu or {}).get('measured_runs', '-')}"
),
],
),
]
width = 1 + len(cols)
lines = ["| Metric | " + " | ".join(cols) + " |", "|" + "---|" * width]
for name, values in rows:
lines.append(f"| {name} | " + " | ".join(values[: len(cols)]) + " |")
if cpu and npu.get("inference_avg_ms") and cpu.get("inference_avg_ms"):
speedup = cpu["inference_avg_ms"] / npu["inference_avg_ms"]
line = f"\nNPU speed-up vs CPU (avg latency): **{speedup:.2f}x**"
if speedup < 1:
line += (
f" - the CPU was faster by {1 / speedup:.2f}x (expected for "
"tiny models: per-inference NPU dispatch overhead dominates)"
)
lines.append(line)
return "\n".join(lines)
def main(argv=None) -> int:
args = parse_args(argv)
# Agents usually capture stdout through a pipe; without this, progress lines
# are block-buffered and only appear when the script exits.
try:
sys.stdout.reconfigure(line_buffering=True)
except (AttributeError, ValueError):
pass
model = pathlib.Path(args.model).expanduser().resolve()
if not model.is_file():
print(f"ERROR: --model {model} not found.", file=sys.stderr)
return 2
minfo = inspect_model(model)
if not minfo["is_tflite"]:
print(f"ERROR: {model} is not a .tflite flatbuffer.", file=sys.stderr)
return 2
if minfo["legacy_ops"]:
print(legacy_model_error(model, minfo["legacy_ops"], "--model"),
file=sys.stderr)
return 2
if not minfo["compiled"]:
print(
f"ERROR: {model} is not AOT-compiled (no DISPATCH_OP/LiteRtStamp). "
"An uncompiled model cannot run on the Google Tensor TPU; compile it "
"first with scripts/compile_model.py.",
file=sys.stderr,
)
return 2
cpu_model = None
if args.cpu_baseline:
cpu_model = pathlib.Path(args.cpu_baseline).expanduser().resolve()
if not cpu_model.is_file():
print(f"ERROR: --cpu-baseline {cpu_model} not found.", file=sys.stderr)
return 2
cinfo = inspect_model(cpu_model)
if cinfo["is_tflite"] and cinfo["legacy_ops"]:
print(legacy_model_error(cpu_model, cinfo["legacy_ops"],
"--cpu-baseline"), file=sys.stderr)
return 2
if not cinfo["is_tflite"] or cinfo["compiled"]:
print(
"ERROR: --cpu-baseline must be the ORIGINAL uncompiled .tflite; a "
"compiled model contains NPU-only DISPATCH_OP nodes and cannot run "
"on the CPU.",
file=sys.stderr,
)
return 2
if args.signature:
# Signature keys are stored verbatim in the flatbuffer, so a missing byte
# string is a reliable "no such signature". benchmark_model itself only
# prints a bare "Benchmarking failed." in that case (seen on device).
key = args.signature.encode()
for p in [model] + ([cpu_model] if cpu_model else []):
if key not in p.read_bytes():
print(
f"ERROR: signature '{args.signature}' not found in {p.name} "
"(no such signature key in the flatbuffer). Omit --signature "
"to run the main subgraph, or check the model's signature list.",
file=sys.stderr,
)
return 2
stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
out_dir = (
pathlib.Path(args.output_dir).expanduser().resolve()
if args.output_dir
else pathlib.Path.cwd() / "litert_benchmark_results" / stamp
)
scratch = pathlib.Path(tempfile.mkdtemp(prefix="litert_gt_bench_"))
base_dir = args.device_dir.rstrip("/") or DEFAULT_DEVICE_DIR
# One fresh sub-directory per run: users often keep their own binaries and
# models in the base directory, and the cleanup must never touch those.
device_dir = f"{base_dir}/run-{stamp}-{os.getpid()}"
base_existed = True # only remove the base dir if this run created it
pushed = False
adb = None
# Agents' tool runners usually SIGTERM a command on timeout; turn that (and
# SIGHUP) into an exception so the ``finally`` cleanup below still runs.
def _terminate(signum, frame):
del frame # Unused.
raise SystemExit(128 + signum)
for sig in ("SIGTERM", "SIGHUP"):
if hasattr(signal, sig):
signal.signal(getattr(signal, sig), _terminate)
try:
serial = args.serial if args.dry_run else pick_device(args.serial)
adb = Adb(serial, args.dry_run)
soc_prop = adb.getprop("ro.soc.model")
device_target = SOC_PROP_TO_TARGET.get(soc_prop.strip().lower())
device = {
"serial": serial or "(dry-run)",
"product_model": adb.getprop("ro.product.model"),
"soc_model": soc_prop,
"target": device_target,
"android_version": adb.getprop("ro.build.version.release"),
"abi": adb.getprop("ro.product.cpu.abi"),
}
if not args.dry_run:
print(
f"Device: {device['product_model']} ({serial}), SoC "
f"'{soc_prop}' -> {device_target or 'unknown target'}, Android "
f"{device['android_version']}, ABI {device['abi']}"
)
if device["abi"] and device["abi"] != "arm64-v8a":
raise BenchmarkError(
3,
f"device ABI {device['abi']} is not arm64-v8a; "
"the prebuilt benchmark_model is android_arm64.",
)
if device_target is None:
print(
f"WARNING: unrecognised ro.soc.model '{soc_prop}'; cannot verify "
"that the model matches this device."
)
elif device_target not in minfo["soc_models"]:
msg = (
f"model is compiled for {', '.join(minfo['soc_models'])} but "
f"the device is {device_target}. Recompile the ORIGINAL "
f"(uncompiled) model with --target {device_target}; there is no "
"runtime fallback."
)
if not args.allow_mismatch:
raise BenchmarkError(4, msg)
print("WARNING (--allow-mismatch): " + msg)
dispatch_url = args.dispatch_url or (
args.benchmark_url.rsplit("/", 1)[0] + "/" + DISPATCH_LIB_NAME
if args.benchmark_url
else None
)
dispatch_lib, dispatch_src = resolve_dispatch_lib(
args.dispatch_lib,
scratch,
dispatch_url,
args.refresh_binary,
dry_run=args.dry_run,
)
bench_bin, bench_src = resolve_benchmark_bin(
args.benchmark_bin,
args.benchmark_url,
args.refresh_binary,
dry_run=args.dry_run,
)
# Same precedence as the resolvers: a local file wins over any URL.
bench_release = runtime_release(
bool(args.benchmark_bin), args.benchmark_url
)
dispatch_release = runtime_release(
bool(args.dispatch_lib or os.environ.get(DISPATCH_LIB_ENV)),
dispatch_url,
)
remote_bin = f"{device_dir}/benchmark_model"
remote_model = f"{device_dir}/{safe_name(model)}"
remote_cpu_model = (
f"{device_dir}/{safe_name(cpu_model)}" if cpu_model else None
)
npu_flags = build_npu_args(args, remote_model, device_dir)
cpu_flags = build_cpu_args(args, remote_cpu_model) if cpu_model else None
# Hooked pass: the NPU run once more with the dispatch library's hooks
# (TPU tile time and/or TPU energy) enabled through a config file in the
# per-run directory; the hooks' reports go there too, so the normal
# cleanup removes everything.
remote_hook_config = f"{device_dir}/{HOOK_CONFIG_NAME}"
remote_tile_report = f"{device_dir}/{TILE_REPORT_NAME}"
remote_power_report = f"{device_dir}/{POWER_REPORT_NAME}"
hook_env = f"{HOOK_ENV}={shlex.quote(remote_hook_config)}"
tile = {"status": "skipped", "reason": "--no-tile-time"}
power = {"status": "skipped", "reason": "--no-power"}
want_tile, want_power = not args.no_tile_time, not args.no_power
if (want_tile or want_power) and re.search(r'[\s"]', device_dir):
bad_dir = {
"status": "unavailable",
"reason": (
"the device directory contains whitespace or a double "
"quote, which the hook's config parser cannot handle (pick "
"another --device-dir)"
),
}
if want_tile:
tile = dict(bad_dir)
if want_power:
power = dict(bad_dir)
want_tile = want_power = False
if want_power and power_hook_is_old(dispatch_lib):
power = {"status": "unavailable", "reason": _OLD_POWER_HOOK_REASON}
want_power = False
hook_flags = build_tile_args(npu_flags) if want_tile or want_power else None
metric_names = (("TPU tile time", want_tile), ("TPU energy", want_power))
hook_label = " + ".join(name for name, on in metric_names if on)
print(f"Benchmark binary: {bench_src}")
print(f"Dispatch library: {dispatch_src}")
print(f"Device scratch dir: {device_dir}")
print(f"Logs/results dir: {out_dir}")
print("\nPushing files ...")
if not args.dry_run:
base_existed = (
adb.shell(f"test -d {shlex.quote(base_dir)}", check=False).returncode
== 0
)
adb.shell(f"mkdir -p {shlex.quote(device_dir)}")
pushed = True
adb.run("push", str(bench_bin), remote_bin, timeout=300)
adb.shell(f"chmod 755 {shlex.quote(remote_bin)}")
adb.run(
"push",
str(dispatch_lib),
f"{device_dir}/{DISPATCH_LIB_NAME}",
timeout=300,
)
adb.run("push", str(model), remote_model, timeout=600)
if cpu_model:
adb.run("push", str(cpu_model), remote_cpu_model, timeout=600)
if hook_flags:
local_hook_config = scratch / HOOK_CONFIG_NAME
local_hook_config.write_text(
hook_config(device_dir, want_tile, want_power)
)
adb.run("push", str(local_hook_config), remote_hook_config, timeout=60)
if args.dry_run:
run_benchmark(adb, remote_bin, npu_flags, scratch / "x", 1, "NPU")
if hook_flags:
run_benchmark(
adb,
remote_bin,
hook_flags,
scratch / "t",
1,
hook_label,
env=hook_env,
)
print(
f" [dry-run] {HOOK_CONFIG_NAME} pushed above:\n"
+ "\n".join(
f" {line}"
for line in hook_config(
device_dir, want_tile, want_power
).splitlines()
)
)
if not want_tile and tile["status"] != "skipped":
print(f" [dry-run] TPU tile time: {tile_time_text(tile)}")
if not want_power and power["status"] != "skipped":
print(f" [dry-run] TPU energy: {power_text(power)}")
if cpu_flags:
run_benchmark(adb, remote_bin, cpu_flags, scratch / "y", 1, "CPU")
print(
"\n--dry-run: nothing was executed on the device and nothing was "
"pushed; the adb commands above (and the cleanup command printed "
"below) are what the real run would execute. The device was NOT "
"contacted, so the SoC/ABI match was not verified; the real run "
"does that first."
)
return 0
out_dir.mkdir(parents=True, exist_ok=True)
thermal = read_thermal(adb)
print(f"Thermal before NPU run: {thermal_text(thermal)}")
code, text = run_benchmark(
adb, remote_bin, npu_flags, out_dir / "npu.log", args.timeout, "NPU"
)
npu = parse_benchmark_log(text)
timed_out = code == 124
retried_without_profiler = False
if (
(code != 0 or "inference_avg_ms" not in npu)
and not args.no_profiler
and not timed_out
and not output_unrecognized(code, text, npu)
):
print(
"NPU run failed with --use_profiler=true; retrying without the "
"profiler (first attempt's log kept as npu_profiled_attempt.log) ..."
)
(out_dir / "npu.log").rename(out_dir / "npu_profiled_attempt.log")
retry_flags = [f for f in npu_flags if f != "--use_profiler=true"]
code, text = run_benchmark(
adb, remote_bin, retry_flags, out_dir / "npu.log", args.timeout, "NPU"
)
npu = parse_benchmark_log(text)
timed_out = code == 124
retried_without_profiler = True
npu_text = text
if code != 0 or "inference_avg_ms" not in npu:
if timed_out:
raise BenchmarkError(
6,
f"NPU benchmark did not finish within --timeout {args.timeout}s "
"(the adb process was killed, which also ends benchmark_model on "
"the phone). Raise --timeout, or lower --num-runs / "
"--extra-arg=--max_secs=N.",
)
if output_unrecognized(code, text, npu):
raise BenchmarkError(
6,
unrecognized_output_error(
"NPU",
text,
bench_src,
out_dir / "npu.log",
retried_without_profiler,
),
)
tail = "\n".join(text.splitlines()[-40:])
raise BenchmarkError(
6,
f"NPU benchmark failed (exit {code}). Last lines:\n{tail}\n"
f"Full log: {out_dir / 'npu.log'}",
)
if npu.get("profile_summary"):
(out_dir / "npu_profile.txt").write_text(npu["profile_summary"])
# Hooked-pass problems are reported in the header, never fatal: the NPU
# latency results are already complete at this point.
hook_text = None
if hook_flags:
code, hook_text = run_benchmark(
adb,
remote_bin,
hook_flags,
out_dir / "tile_time.log",
args.timeout,
hook_label,
env=hook_env,
)
tile_report = power_report = ""
if code != 124:
if want_tile:
tile_report = read_device_file(adb, remote_tile_report)
if _TILE_TOTAL_RE.search(tile_report):
(out_dir / "tile_time_report.txt").write_text(tile_report)
if want_power:
power_report = read_device_file(adb, remote_power_report)
if _POWER_TOTAL_RE.search(power_report):
(out_dir / "power_report.txt").write_text(power_report)
if want_tile:
tile = analyze_tile_pass(code, hook_text, tile_report)
tile.update(flags=hook_flags, env=hook_env)
print(f"TPU tile time: {tile_time_text(tile)}")
if want_power:
power = analyze_power_pass(code, hook_text, power_report)
power.update(flags=hook_flags, env=hook_env)
print(f"TPU energy: {power_text(power)}")
cpu = None
cpu_text = None
if cpu_flags:
code, text = run_benchmark(
adb, remote_bin, cpu_flags, out_dir / "cpu.log", args.timeout, "CPU"
)
cpu = parse_benchmark_log(text)
cpu_text = text
if code != 0 or "inference_avg_ms" not in cpu:
if output_unrecognized(code, text, cpu):
reason = (
"benchmark_model exited 0 but its output format was not "
"recognized, see _PATTERNS"
)
else:
reason = f"exit {code}"
print(
f"WARNING: CPU baseline failed ({reason}); see "
f"{out_dir / 'cpu.log'}. Reporting NPU only."
)
cpu = None
elif cpu.get("profile_summary"):
(out_dir / "cpu_profile.txt").write_text(cpu["profile_summary"])
log_checks = {
"npu.log": check_log(npu_text),
"cpu.log": check_log(cpu_text) if cpu_text is not None else None,
}
if hook_text is not None:
log_checks["tile_time.log"] = check_log(hook_text)
npu_only_rows = []
if tile["status"] != "skipped":
npu_only_rows.append((
"TPU tile time / inference (ms)",
fmt(tile.get("per_inference_ms"), 3),
))
if power["status"] != "skipped":
npu_only_rows.append((
"TPU energy / inference (mJ)",
fmt(power.get("per_inference_mj"), 3),
))
soc_label = device_target or "/".join(minfo["soc_models"]) or "NPU"
table = markdown_table(
{k: v for k, v in npu.items() if k != "profile_summary"},
{k: v for k, v in cpu.items() if k != "profile_summary"}
if cpu
else None,
model.name,
cpu_model.name if cpu_model else None,
soc_label,
npu_only_rows,
)
mode = (
"NPU with CPU fallback allowed (--allow-cpu-fallback)"
if args.allow_cpu_fallback
else "strict NPU (--use_cpu=false --require_full_delegation=true)"
)
# Compile provenance: only from compile_model.py's sidecar, never guessed.
sidecar = read_compile_sidecar(model)
if sidecar:
flags = " ".join(sidecar.get("cli_flags") or []) or "(compiler defaults)"
if sidecar.get("ops_total") is not None:
ops_text = (
f"{sidecar.get('ops_offloaded')} / {sidecar['ops_total']} "
"ops offloaded"
)
else:
ops_text = "op counts not recorded"
compile_text = f"{flags}; {ops_text} (from {model.name}.compile.json)"
else:
compile_text = (
f"unknown - no {model.name}.compile.json next to the "
"model (compiled elsewhere); see Delegation below"
)
versions_text, versions_entry = versions_summary(
sidecar, bench_release, dispatch_release
)
if "delegated_nodes" in npu:
delegation_text = (
f"{npu['delegated_nodes']} of {npu['total_nodes']} "
f"node(s) replaced by {npu.get('delegate')} at run "
"time"
)
if npu["delegated_nodes"] != npu["total_nodes"]:
delegation_text += " - NOT fully delegated"
else:
delegation_text = "no 'Replacing N out of M node(s)' line in npu.log"
# Every value below comes from the device or this run; the report in
# SKILL.md is meant to be this block pasted verbatim. Paths under the
# current directory are shown relative to it to keep the block readable;
# results.json keeps the full strings.
cwd_prefix = os.getcwd().rstrip(os.sep) + os.sep
def _short(text: str) -> str:
return text.replace(cwd_prefix, "")
retry_text = (
"yes - the profiled attempt failed, see npu_profiled_attempt.log"
if retried_without_profiler
else "none"
)
log_check_line = "; ".join(
log_check_text(name, chk) for name, chk in log_checks.items()
)
header = (
f"**Device:** {device['product_model']} (serial {serial}), "
f"SoC {soc_prop}, Android {device['android_version']} \n"
f"**Model:** {model.name} ({fmt_size(minfo['size_bytes'])}, "
f"compiled for {'/'.join(minfo['soc_models']) or 'unknown SoC'}) \n"
f"**Compile:** {compile_text} \n"
f"**Versions:** {versions_text} \n"
f"**Delegation (runtime):** {delegation_text} \n"
f"**Mode:** {mode}; requested {args.warmup_runs} warmup / "
f"{args.num_runs} measured runs (actual counts in the table) \n"
f"**Thermal before NPU run:** {thermal_text(thermal)} \n"
f"**TPU tile time:** {tile_time_text(tile)} \n"
f"**TPU energy:** {power_text(power)} \n"
f"**Benchmark binary:** {_short(bench_src)} \n"
f"**Dispatch library:** {_short(dispatch_src)} \n"
f"**NPU flags:** `{' '.join(npu_flags)}` \n"
f"**Log check:** {log_check_line}; profiler retry: {retry_text} \n"
f"**Logs:** {_short(str(out_dir))}"
)
report_md = header + "\n\n" + table + unexpected_lines_md(log_checks)
print("\n" + report_md)
if cpu:
cpu_entry = {
"model": str(cpu_model),
"flags": cpu_flags,
**{k: v for k, v in cpu.items() if k != "profile_summary"},
}
else:
cpu_entry = None
results = {
"timestamp": stamp,
"device": device,
"thermal_before_npu_run": thermal,
"benchmark_binary": bench_src,
"dispatch_library": dispatch_src,
"model": {
"path": str(model),
"size_bytes": minfo["size_bytes"],
"soc_models": minfo["soc_models"],
},
"compile": sidecar,
"versions": versions_entry,
"npu": {
"flags": npu_flags,
**{k: v for k, v in npu.items() if k != "profile_summary"},
},
"cpu": cpu_entry,
"tpu_tile_time": tile,
"tpu_energy": power,
"log_check": {
**log_checks,
"retried_without_profiler": retried_without_profiler,
},
"markdown": report_md,
}
(out_dir / "results.json").write_text(json.dumps(results, indent=2))
# The same block as a file, so "save the report" needs no retyping.
(out_dir / "report.md").write_text(report_md + "\n")
print(f"\nWrote {out_dir / 'results.json'} and {out_dir / 'report.md'}")
return 0
except BenchmarkError as e:
print(f"ERROR: {e}", file=sys.stderr)
return e.code
except KeyboardInterrupt:
print(
"\nInterrupted (Ctrl-C); cleaning up the device directory ...",
file=sys.stderr,
)
return 130
finally:
# Runs on success, errors, Ctrl-C (KeyboardInterrupt) and SIGTERM/SIGHUP
# (SystemExit from _terminate). Killing the local adb client also ends
# benchmark_model on the phone (verified: no process left behind).
if adb is not None and pushed and not args.keep_device_files:
try:
adb.shell(f"rm -rf {shlex.quote(device_dir)}", check=False, timeout=60)
if not base_existed:
# rmdir only succeeds on an empty directory, so this can never take
# anything else with it.
adb.shell(f"rmdir {shlex.quote(base_dir)}", check=False, timeout=30)
if not args.dry_run:
print(f"Cleaned up {device_dir} on the device.")
except Exception as e: # pylint: disable=broad-exception-caught
print(
f"WARNING: device cleanup failed: {e}. Run: adb shell rm -rf "
f"{device_dir}",
file=sys.stderr,
)
elif adb is not None and pushed and not args.dry_run:
print(
f"Kept device files in {device_dir} (--keep-device-files). Remove "
f"with: adb shell rm -rf {device_dir}"
)
shutil.rmtree(scratch, ignore_errors=True)
if __name__ == "__main__":
sys.exit(main())
check_compiled.py 7.8 KB
#!/usr/bin/env python3
# Copyright 2026 The Google AI Edge Authors. All Rights Reserved.
#
# 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.
"""Reports whether a .tflite file is AOT-compiled for a Google Tensor TPU.
Dependency-free (standard library only), so it can run in any Python 3
environment before the LiteRT packages are installed.
Detection method
----------------
LiteRT's ahead-of-time compiler rewrites NPU partitions into a custom op named
``DISPATCH_OP`` and stamps the flatbuffer with a metadata entry keyed
``LiteRtStamp`` that records the SoC manufacturer (``Google``) and SoC model
(``Tensor_G5``, ``Tensor_G6``, ...). Both markers are plain byte strings, so a
byte search is sufficient and robust.
Models compiled by another toolchain - the Edge TPU compiler, or older
Google Tensor tooling that emits the same op - hold an ``edgetpu-custom-op``
custom op instead (e.g. ``edgetpu-custom-op-2``). They are neither plain nor
LiteRT builds: LiteRT cannot recompile or benchmark them on the Google Tensor
TPU, and the CPU cannot run them.
Exit codes
----------
0 compiled (and matches --expect-target when given)
1 valid .tflite that is NOT compiled (plain CPU/GPU model)
2 compiled, but for a different SoC than --expect-target
3 file missing / not a .tflite flatbuffer
4 compiled by another toolchain (Edge TPU custom op): not usable here
"""
from __future__ import annotations
import argparse
import json
import pathlib
import re
import sys
from typing import Any
TFLITE_FILE_IDENTIFIER = b"TFL3" # flatbuffer identifier at byte offset 4..8
DISPATCH_OP_MARKER = b"DISPATCH_OP"
BUILD_STAMP_KEY = b"LiteRtStamp"
GOOGLE_MANUFACTURER = b"Google"
SOC_MODEL_RE = re.compile(rb"Tensor_G\d+")
# Custom op of models compiled by the Edge TPU compiler (and older Google
# Tensor tooling): edgetpu-custom-op, edgetpu-custom-op-2, ...
LEGACY_TPU_OP_RE = re.compile(rb"edgetpu-custom-op[\w-]*")
# Targets this skill supports (same list as compile_model.py --target). Any
# ``Tensor_G<n>`` stamp is still identified and printed, so artifacts compiled
# for an older SoC are reported by name instead of as "unknown".
SUPPORTED_TARGETS = ("Tensor_G5", "Tensor_G6")
def fmt_size(num_bytes: int) -> str:
"""'8,110,864 bytes (8.1 MB)'; MB = 10^6 bytes, same as compile/benchmark."""
text = f"{num_bytes:,} bytes"
if num_bytes >= 100_000:
text += f" ({num_bytes / 1e6:.1f} MB)"
return text
def _read_sidecar(path: pathlib.Path) -> dict[str, Any] | None:
"""Loads the ``<model>.compile.json`` written by compile_model.py, if any."""
if not path.is_file():
return None
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
return data if isinstance(data, dict) else None
def inspect_model(path: pathlib.Path) -> dict[str, Any]:
"""Returns a dict describing the compilation state of ``path``."""
data = path.read_bytes()
is_tflite = len(data) >= 8 and data[4:8] == TFLITE_FILE_IDENTIFIER
has_dispatch_op = DISPATCH_OP_MARKER in data
has_stamp = BUILD_STAMP_KEY in data
soc_models = sorted({m.decode("ascii") for m in SOC_MODEL_RE.findall(data)})
compiled = is_tflite and has_dispatch_op and has_stamp
legacy_ops = sorted({m.decode("ascii")
for m in LEGACY_TPU_OP_RE.findall(data)})
return {
"path": str(path),
"size_bytes": len(data),
"is_tflite": is_tflite,
"compiled": compiled,
"has_dispatch_op": has_dispatch_op,
"has_build_stamp": has_stamp,
"google_tensor": GOOGLE_MANUFACTURER in data and bool(soc_models),
"soc_models": soc_models,
# Compiled by another toolchain (Edge TPU custom op), not by LiteRT.
"legacy_compiled": is_tflite and not compiled and bool(legacy_ops),
"legacy_ops": legacy_ops,
}
def main(argv=None) -> int:
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("model", help="Path to the .tflite file to inspect.")
parser.add_argument(
"--expect-target",
choices=SUPPORTED_TARGETS,
help=(
"SoC the model should be compiled for (the attached phone's "
"ro.soc.model: 'Tensor G5' -> Tensor_G5). Exit 2 if the model is "
"compiled for a different SoC."
),
)
parser.add_argument(
"--json", action="store_true", help="Print machine-readable JSON only."
)
parser.add_argument(
"--dry-run",
action="store_true",
help=(
"Accepted for consistency with the other scripts; this check is "
"read-only, so it changes nothing."
),
)
args = parser.parse_args(argv)
path = pathlib.Path(args.model).expanduser()
if not path.is_file():
print(f"ERROR: file not found: {path}", file=sys.stderr)
return 3
info = inspect_model(path)
if not info["is_tflite"]:
info["verdict"] = "not_tflite"
if args.json:
print(json.dumps(info, indent=2))
else:
print(
f"ERROR: {path} is not a .tflite flatbuffer (missing 'TFL3' "
"identifier).",
file=sys.stderr,
)
return 3
if info["legacy_compiled"]:
info["verdict"] = "legacy_compiled"
code = 4
elif not info["compiled"]:
info["verdict"] = "not_compiled"
code = 1
elif args.expect_target and args.expect_target not in info["soc_models"]:
info["verdict"] = "target_mismatch"
code = 2
else:
info["verdict"] = "compiled"
code = 0
if args.json:
print(json.dumps(info, indent=2))
return code
print(f"Model: {path} ({fmt_size(info['size_bytes'])})")
if code == 4:
print(
"Status: compiled by ANOTHER toolchain - it holds an Edge TPU custom "
f"op ({', '.join(info['legacy_ops'])}), not LiteRT's DISPATCH_OP. "
"LiteRT cannot recompile it or run it on the Google Tensor TPU, and "
"the CPU cannot run it, so do not use it for compiling, "
"benchmarking, --cpu-baseline or an app. Get the ORIGINAL model it "
"was compiled from and compile that with scripts/compile_model.py."
)
elif code == 1:
print(
"Status: NOT compiled - plain model (no DISPATCH_OP / LiteRtStamp "
"markers). Use it as-is for --cpu-baseline or CPU/GPU runs; compile "
"it with scripts/compile_model.py before benchmarking on the Google "
"Tensor TPU."
)
else:
socs = ", ".join(info["soc_models"]) or "unknown"
print(f"Status: compiled for Google Tensor (SoC: {socs})")
sidecar = path.with_name(path.name + ".compile.json")
compile_info = _read_sidecar(sidecar)
if compile_info:
flags = compile_info.get("cli_flags") or ["(compiler defaults)"]
ops = compile_info.get("ops_offloaded"), compile_info.get("ops_total")
ops_text = (
f"{ops[0]} / {ops[1]} ops offloaded"
if None not in ops
else "op counts not recorded"
)
print(f"Compile info ({sidecar.name}): {' '.join(flags)}; {ops_text}")
else:
print(
"Note: the stamp records the SoC only, not the compiler flags "
f"(no {sidecar.name} next to the model)."
)
if code == 2:
print(
f"WARNING: expected {args.expect_target}; this model will not "
"run on that device's TPU. Recompile the ORIGINAL (uncompiled) "
"model for the right target."
)
return code
if __name__ == "__main__":
sys.exit(main())
compile_model.py 63.8 KB
#!/usr/bin/env python3
# Copyright 2026 The Google AI Edge Authors. All Rights Reserved.
#
# 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.
"""AOT-compiles a .tflite model for a Google Tensor TPU (Tensor_G5 / Tensor_G6).
Thin, reproducible wrapper around the public LiteRT Python AOT API:
from ai_edge_litert.aot import aot_compile as aot_lib
from ai_edge_litert.aot.vendors.google_tensor import target as gt_target
aot_lib.aot_compile(model, output_dir=..., target=gt_target.Target(...),
keep_going=False, google_tensor_<flag>=...)
Requirements (see SKILL.md):
* Local compile: Linux x86_64 host (the Google Tensor compiler plugin only
ships for it) and a virtualenv with ``ai-edge-litert`` +
``ai-edge-litert-sdk-google-tensor`` installed with
``GOOGLE_TENSOR_SDK_BETA`` pointing at the Beta compiler tarball (Google
Tensor SDK Beta access required). Without the tarball the SDK package has
no compiler library and this script exits with 5.
* Remote Colab compile (``--colab``, any host OS including macOS/Windows):
``google-colab-cli`` (``colab``) on PATH and the Beta compiler tarball
(``--sdk-tarball`` or ``GOOGLE_TENSOR_SDK_BETA``; or ``--sdk-url`` /
``GOOGLE_TENSOR_ML_SDK_URL``). Provisions a Colab Linux x86_64 VM, uploads
this script, ``versions.json``, the model and the tarball, installs the
pinned LiteRT pair on the VM, compiles there, downloads ``<output>.tflite``
and ``<output>.compile.json``, and stops the VM.
* ``--print-install`` (add ``--colab`` for the Colab setup) prints the
install commands for the version pinned in the skill's ``versions.json``
(any python3, any host, no LiteRT needed).
The script sets GOOGLE_TENSOR_BACKEND_ENABLED=1 before importing LiteRT; the
public Tensor SDK FAQ requires it when using the stable ``ai-edge-litert``
package (it is harmless otherwise). Before compiling it compares the installed
LiteRT packages: a WARNING when ``ai-edge-litert`` and the SDK package differ,
a NOTE when they differ from the pin in ``versions.json``.
Output: ``<output-dir>/<model-stem>_Google_<target>.tflite`` (override with
--output-name; an existing file is never overwritten unless --overwrite is
given) plus a ``<output>.compile.json`` sidecar recording the flags, the
compiler's partition report (ops offloaded / total), the package versions and
checksums, so later reports do not depend on anyone retyping them. The
partition report is also printed on stdout.
Exit codes
----------
0 success 5 LiteRT packages, Beta compiler library or
2 bad arguments or input file google-colab-cli (--colab) missing
3 model is already compiled 6 compilation failed
(by LiteRT, or by another 7 output verification failed
toolchain: Edge TPU op)
4 unsupported host platform
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import pathlib
import platform
import re
import shutil
import signal
import subprocess
import sys
import tarfile
import tempfile
import time
from typing import Any
SUPPORTED_TARGETS = ("Tensor_G5", "Tensor_G6")
TRUNCATION_TYPES = ("auto", "bfloat16", "half", "no_truncation")
SHARDING_INTENSITIES = ("minimal", "moderate", "extensive", "maximum")
COLAB_AUTH_MODES = ("oauth2", "adc")
COLAB_BIN_ENV = "LITERT_GOOGLE_TENSOR_COLAB_BIN"
COLAB_EXIT_MARKER = "LITERT_COLAB_EXIT_CODE="
COLAB_PROBE_MARKER = "LITERT_COLAB_PROBE="
PUBLIC_COLAB_TUTORIAL = (
"https://github.com/google-ai-edge/litert-samples/blob/main/"
"samples/litert/colab/LiteRT_AOT_Compilation_Tutorial.ipynb"
)
TFLITE_FILE_IDENTIFIER = b"TFL3"
DISPATCH_OP_MARKER = b"DISPATCH_OP"
BUILD_STAMP_KEY = b"LiteRtStamp"
# Custom op of models compiled by the Edge TPU compiler (and older Google
# Tensor tooling), same check as check_compiled.py.
LEGACY_TPU_OP_RE = re.compile(rb"edgetpu-custom-op[\w-]*")
SOC_MODEL_RE = re.compile(rb"Tensor_G\d+")
# "Subgraph 0 fully compiled:\t175 / 175 ops offloaded to 1 partitions."
PARTITION_RE = re.compile(
r"(\d+)\s*/\s*(\d+)\s+ops offloaded to\s+(\d+)\s+partitions"
)
# Name of the native compiler shipped in the Beta SDK tarball; the LiteRT
# wheel's plugin adapter dlopens it from the SDK package's data/ directory.
COMPILER_LIB_NAME = "liblitert_plugin_compiler.so"
# The skill's single source of LiteRT versions (change it only as described in
# references/contributing.md). Nothing in this script hard-codes a version.
VERSIONS_FILE = (
pathlib.Path(__file__).resolve().parent.parent / "assets" / "versions.json"
)
# (runtime package, Google Tensor SDK package); the two must be one version.
LITERT_PAIRS = (
("ai-edge-litert", "ai-edge-litert-sdk-google-tensor"),
("ai-edge-litert-nightly", "ai-edge-litert-sdk-google-tensor-nightly"),
)
DEFAULT_VENV = "~/.venvs/litert-tensor"
TARBALL_PLACEHOLDER = "/abs/path/litert_plugin_compiler.tar.gz"
def load_versions() -> dict[str, Any]:
"""Reads versions.json; raises ValueError with a readable message."""
try:
data = json.loads(VERSIONS_FILE.read_text(encoding="utf-8"))
except (OSError, ValueError) as e:
raise ValueError(f"cannot read {VERSIONS_FILE}: {e}") from e
if not isinstance(data, dict):
raise ValueError(f"{VERSIONS_FILE} must hold a JSON object")
release = data.get("pip_release")
if not isinstance(release, str) or not re.fullmatch(
r"\d[0-9A-Za-z.+!_-]*", release
):
raise ValueError(
f"{VERSIONS_FILE}: 'pip_release' must be a version "
"string such as 'X.Y.Z'"
)
if not isinstance(data.get("python"), str):
raise ValueError(
f"{VERSIONS_FILE}: 'python' must be a range string "
"'MAJOR.MINOR-MAJOR.MINOR'"
)
return data
def pip_install_line(release: str) -> str:
return (
f"pip install --no-cache-dir ai-edge-litert=={release} "
f"ai-edge-litert-sdk-google-tensor=={release}"
)
def install_hint(release: str | None) -> str:
"""Install instructions for the exit-5 messages, with the pinned version."""
pip_line = (
pip_install_line(release)
if release
else pip_install_line("<V>") + f" # <V>: pip_release in {VERSIONS_FILE}"
)
return (
"The Google Tensor compiler ships as a Beta SDK tarball"
" (litert_plugin_compiler.tar.gz) that you receive by email after"
" signing up at\n "
" https://services.google.com/fb/forms/tensor_ml_sdk_experimental_access\nInstall"
" it inside a virtualenv (Linux x86_64 only; compile_model.py"
" --print-install prints every command):\n export"
f" GOOGLE_TENSOR_SDK_BETA={TARBALL_PLACEHOLDER}\n {pip_line}\n(add"
" --force-reinstall when the packages are already installed;"
" --no-cache-dir matters because pip otherwise reuses a previously built"
" SDK wheel that has no compiler library in it.)"
)
def colab_install_hint(release: str | None) -> str:
"""Install instructions for remote Colab compilation (--colab)."""
ver = release or f"<V> (pip_release in {VERSIONS_FILE})"
return (
"To compile on a remote Google Colab Linux x86_64 VM (--colab):\n"
" 1. Install google-colab-cli (https://github.com/googlecolab/"
"google-colab-cli):\n"
" uv tool install google-colab-cli # or: pip install "
"google-colab-cli\n"
" 2. Authenticate once (browser OAuth or gcloud ADC):\n"
" colab --auth oauth2 sessions\n"
" or, for headless ADC (--colab-auth adc):\n"
" gcloud auth application-default login --scopes="
"openid,https://www.googleapis.com/auth/cloud-platform,"
"https://www.googleapis.com/auth/userinfo.email,"
"https://www.googleapis.com/auth/colaboratory\n"
" 3. Provide the Beta SDK tarball (litert_plugin_compiler.tar.gz from "
"the sign-up e-mail):\n"
f" export GOOGLE_TENSOR_SDK_BETA={TARBALL_PLACEHOLDER}\n"
" (or pass --sdk-tarball FILE, or --sdk-url URL). The script then "
f"installs ai-edge-litert + ai-edge-litert-sdk-google-tensor {ver} on "
"the Colab VM automatically.\n"
f"Public Colab tutorial: {PUBLIC_COLAB_TUTORIAL}"
)
def _python_range(spec: str) -> tuple[tuple[int, int], tuple[int, int]] | None:
"""'3.10-3.13' -> ((3, 10), (3, 13)); None for any other format."""
m = re.fullmatch(r"\s*(\d+)\.(\d+)\s*-\s*(\d+)\.(\d+)\s*", spec)
if not m:
return None
major_lo, minor_lo, major_hi, minor_hi = (int(x) for x in m.groups())
return (major_lo, minor_lo), (major_hi, minor_hi)
def print_install(colab: bool = False) -> int:
"""--print-install: the pinned install commands, ready to paste."""
try:
versions = load_versions()
except ValueError as e:
print(f"ERROR: {e}", file=sys.stderr)
return 2
release = versions["pip_release"]
host = f"{sys.platform}/{platform.machine()}"
host_ok = sys.platform == "linux" and platform.machine() == "x86_64"
here = platform.python_version()
lines = [
f"# ai-edge-litert + ai-edge-litert-sdk-google-tensor {release} "
f"(pip_release in {VERSIONS_FILE})"
]
verified = versions.get("verified")
if isinstance(verified, dict) and verified:
lines.append(
"# Last verified: "
+ "; ".join(f"{key}: {value}" for key, value in verified.items())
)
if colab or not host_ok:
lines += [
(
f"# Remote Google Colab compile (this host: {host}; no local Linux "
"x86_64 or LiteRT venv needed)."
),
(
"# Uses google-colab-cli"
" (https://github.com/googlecolab/google-colab-cli) and the Beta"
" tarball litert_plugin_compiler.tar.gz (or unpacked"
" google_tensor_ml_sdk/ dir) from the sign-up e-mail."
),
f"# Public Colab tutorial: {PUBLIC_COLAB_TUTORIAL}",
"uv tool install google-colab-cli # or: pip install google-colab-cli",
(
f"python3 {pathlib.Path(__file__).resolve()} /abs/path/model.tflite"
f" --target Tensor_G5 --colab --sdk-tarball {TARBALL_PLACEHOLDER}"
),
]
if colab:
print("\n".join(lines))
return 0
lines.append(
"# --- Or, if you move to a Linux x86_64 machine for local compile: ---"
)
host_note = ""
if not host_ok:
host_note = (
" - NOT supported locally; run these on a Linux x86_64 machine "
"or add --colab to compile on Google Colab"
)
lines.append(
f"# Needs: Linux x86_64 (this host: {host}{host_note}"
f"), Python {versions['python']} (this Python: {here}), and the Beta "
"tarball litert_plugin_compiler.tar.gz from the sign-up e-mail."
)
lines.append(
"# No Linux x86_64 machine? Run with --print-install --colab for the "
"remote Google Colab setup."
)
supported = _python_range(versions["python"])
if supported and not supported[0] <= sys.version_info[:2] <= supported[1]:
lines.append(
f"# WARNING: Python {here} is outside {versions['python']}; "
"create the venv with a Python in that range (e.g. "
f"python{supported[1][0]}.{supported[1][1]} -m venv ...)."
)
lines += [
f"python3 -m venv {DEFAULT_VENV} && source {DEFAULT_VENV}/bin/activate",
"pip install --upgrade pip",
(
f"export GOOGLE_TENSOR_SDK_BETA={TARBALL_PLACEHOLDER}"
" # from the Beta e-mail"
),
pip_install_line(release),
]
print("\n".join(lines))
return 0
def installed_litert_versions() -> dict[str, str]:
"""{distribution: version} of the LiteRT packages in this interpreter."""
found = {}
try:
import importlib.metadata as md # pylint: disable=g-import-not-at-top
except ImportError:
return found
for pair in LITERT_PAIRS:
for dist in pair:
try:
found[dist] = md.version(dist)
except md.PackageNotFoundError:
pass
return found
def version_warnings(
installed: dict[str, str], pinned: str | None
) -> list[tuple[str, str]]:
"""(level, message) pairs about the installed LiteRT packages.
WARNING: a runtime package and its Google Tensor SDK package differ (they
must be one version). NOTE (only without a WARNING): the stable pair is not
the pin in versions.json - allowed, and the sidecar records what was used.
Args:
installed: {distribution: version} from installed_litert_versions().
pinned: The pip_release pinned in versions.json, or None if unavailable.
Returns:
The (level, message) pairs; level is "WARNING" or "NOTE".
"""
reinstall = (
f"{pip_install_line(pinned)} --force-reinstall"
if pinned
else "see compile_model.py --print-install"
)
messages = []
for runtime, sdk in LITERT_PAIRS:
a, b = installed.get(runtime), installed.get(sdk)
if a and b and a != b:
messages.append((
"WARNING",
(
f"{runtime} {a} and {sdk} {b} differ; they "
"must be the same version. Reinstall both with "
f"GOOGLE_TENSOR_SDK_BETA set: {reinstall}"
),
))
stable = LITERT_PAIRS[0]
if (
pinned
and installed
and not messages
and any(installed.get(dist) != pinned for dist in stable)
):
have = [
f"{d} {installed[d]}" if d in installed else f"{d} not installed"
for d in stable
]
have += [f"{d} {v}" for d, v in installed.items() if d not in stable]
messages.append((
"NOTE",
(
f"installed {', '.join(have)}; versions.json pins "
f"{pinned}. The compile uses the installed packages (the "
"sidecar records them). For the pinned pair, with "
f"GOOGLE_TENSOR_SDK_BETA set: {reinstall}"
),
))
return messages
def fmt_size(num_bytes: int) -> str:
"""'8,110,864 bytes (8.1 MB)'; MB = 10^6 bytes, same as the other scripts."""
text = f"{num_bytes:,} bytes"
if num_bytes >= 100_000:
text += f" ({num_bytes / 1e6:.1f} MB)"
return text
def sha256_of(path: pathlib.Path) -> str:
digest = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def _inspect(path: pathlib.Path) -> dict[str, Any]:
data = path.read_bytes()
compiled = DISPATCH_OP_MARKER in data and BUILD_STAMP_KEY in data
return {
"is_tflite": len(data) >= 8 and data[4:8] == TFLITE_FILE_IDENTIFIER,
"compiled": compiled,
"soc_models": sorted({m.decode() for m in SOC_MODEL_RE.findall(data)}),
"size_bytes": len(data),
# Compiled by another toolchain (Edge TPU custom op), not by LiteRT.
"legacy_ops": [] if compiled else sorted(
{m.decode() for m in LEGACY_TPU_OP_RE.findall(data)}),
}
def build_backend_kwargs(args: argparse.Namespace) -> dict[str, Any]:
"""Maps CLI flags to the ``google_tensor_*`` kwargs the backend accepts.
Only flags that differ from the compiler defaults are forwarded, so the
default behaviour is exactly the compiler's documented default behaviour.
Args:
args: Parsed command-line arguments.
Returns:
{kwarg name: value} for aot_compile; empty when every flag is default.
"""
kwargs = {}
if args.truncation_type != "auto":
kwargs["google_tensor_truncation_type"] = args.truncation_type
if args.sharding_intensity:
kwargs["google_tensor_sharding_intensity"] = args.sharding_intensity
if args.int64_to_int32:
kwargs["google_tensor_int64_to_int32"] = True
if args.large_model_support:
kwargs["google_tensor_enable_large_model_support"] = True
if args.enable_4bit:
kwargs["google_tensor_enable_4bit_compilation"] = True
if args.extra_options_path:
kwargs["google_tensor_extra_options_path"] = str(
pathlib.Path(args.extra_options_path).expanduser().resolve()
)
return kwargs
def parse_args(argv=None) -> argparse.Namespace:
"""Parses the command-line arguments (default: sys.argv[1:])."""
p = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
p.add_argument("model", nargs="?", help="Input .tflite model (uncompiled).")
p.add_argument(
"--target",
choices=SUPPORTED_TARGETS,
help=(
"Google Tensor SoC: Tensor_G5 = Pixel 10 family, "
"Tensor_G6 = Pixel 11 family. Required (as is the "
"model) unless --print-install is given."
),
)
p.add_argument(
"--output-dir",
help="Where to write the compiled model (default: <model dir>/compiled).",
)
p.add_argument(
"--output-name",
help="Output file name (default: <model stem>_Google_<target>.tflite).",
)
g = p.add_argument_group(
"Google Tensor compiler flags",
"See references/compile-flags.md. Defaults match "
"the public compiler defaults.",
)
g.add_argument(
"--truncation-type",
default="auto",
choices=TRUNCATION_TYPES,
help="Float precision used on the TPU (default: auto).",
)
g.add_argument(
"--sharding-intensity",
choices=SHARDING_INTENSITIES,
help=(
"How aggressively to split the model for parallelism "
"(compiler default: minimal)."
),
)
g.add_argument(
"--int64-to-int32",
action="store_true",
help="Allow the compiler to narrow int64 to int32.",
)
g.add_argument(
"--large-model-support",
action="store_true",
help="Required for models larger than 2 GB.",
)
g.add_argument(
"--enable-4bit",
action="store_true",
help="Enable compilation of 4-bit convolution weights.",
)
g.add_argument(
"--extra-options-path",
help="Binary file with extra compiler options (advanced).",
)
c = p.add_argument_group(
"Remote Google Colab compilation (any host OS, via google-colab-cli)",
"Use --colab when this machine is not Linux x86_64 (e.g. macOS/Windows) "
"or has no local LiteRT setup. See --print-install --colab.",
)
c.add_argument(
"--colab",
action="store_true",
help=(
"Compile on a remote Google Colab Linux x86_64 VM using "
"google-colab-cli ('colab'). Uploads the model and Beta SDK "
"tarball, runs this script on the VM, downloads the compiled "
".tflite and .compile.json sidecar, and stops the VM."
),
)
c.add_argument(
"--sdk-tarball",
help=(
"Path to litert_plugin_compiler.tar.gz from the Beta e-mail "
"(default: $GOOGLE_TENSOR_SDK_BETA); uploaded by --colab."
),
)
c.add_argument(
"--sdk-url",
help=(
"Download URL for the Beta compiler tarball (default: "
"$GOOGLE_TENSOR_ML_SDK_URL); used by --colab when --sdk-tarball "
"is not set."
),
)
c.add_argument(
"--colab-bin",
help=(
"google-colab-cli executable (default: "
f"${COLAB_BIN_ENV}, else 'colab' on PATH)."
),
)
c.add_argument(
"--colab-auth",
choices=COLAB_AUTH_MODES,
help=(
"Auth mode passed as global --auth to colab (oauth2 or adc; "
"default: colab's own default)."
),
)
c.add_argument(
"--colab-auth-code",
help=(
"One-time Google OAuth authorization code to complete colab login "
"non-interactively (after visiting the URL printed by a previous "
"--colab run)."
),
)
c.add_argument(
"--colab-session",
help=(
"Colab session name to create or reuse (default: "
"litert-gt-<pid>). An already-active session is reused and kept."
),
)
c.add_argument(
"--colab-high-mem",
action="store_true",
help="Request a High-RAM Colab VM (--high-mem; requires Colab Pro).",
)
c.add_argument(
"--keep-colab-session",
action="store_true",
help=(
"Keep a newly created Colab VM running after the compile so a "
"later --colab-session NAME run can skip installing the SDK."
),
)
c.add_argument(
"--colab-timeout",
type=int,
default=900,
help=(
"Timeout in seconds for the remote Colab compile step (default: 900)."
),
)
p.add_argument(
"--keep-going",
action="store_true",
help="Continue past backend errors instead of failing fast.",
)
p.add_argument(
"--keep-intermediates",
action="store_true",
help=(
"Keep the compiler's intermediate files under "
"<output-dir>/_intermediates."
),
)
p.add_argument(
"--overwrite",
action="store_true",
help=(
"Replace an existing output file (default: refuse with "
"exit 2 so a previous artifact is never clobbered)."
),
)
p.add_argument(
"--no-report-file",
action="store_true",
help="Do not write the <output>.compile.json sidecar.",
)
p.add_argument(
"--force",
action="store_true",
help=(
"(experimental) Skip the already-compiled check. The "
"compiler cannot recompile DISPATCH_OP partitions, so "
"this normally fails; compile the original export "
"instead."
),
)
p.add_argument(
"--dry-run",
action="store_true",
help="Validate inputs and print the plan; do not compile.",
)
p.add_argument(
"--json",
action="store_true",
help="Print a JSON summary as the last line of stdout.",
)
p.add_argument(
"--print-install",
action="store_true",
help=(
"Print the commands that install the LiteRT packages "
"pinned in the skill's versions.json into a new "
"virtualenv (or, with --colab, the google-colab-cli "
"setup), then exit (exit 2 if versions.json is "
"unreadable). Needs no LiteRT, works on any host and "
"ignores the other arguments."
),
)
args = p.parse_args(argv)
if not args.print_install:
missing = [
name
for name, value in (("model", args.model), ("--target", args.target))
if not value
]
if missing:
p.error("the following arguments are required: " + ", ".join(missing))
return args
def _safe_name(name: str) -> str:
return re.sub(r"[^A-Za-z0-9._-]", "_", name)
def _resolve_colab_bin(explicit: str | None) -> str | None:
"""Locates the google-colab-cli executable."""
candidate = explicit or os.environ.get(COLAB_BIN_ENV)
if candidate:
found = shutil.which(candidate)
if found:
return found
p = pathlib.Path(candidate).expanduser()
return str(p.resolve()) if p.is_file() else None
found = shutil.which("colab")
if found:
return found
for fallback in (
pathlib.Path.home() / ".local" / "bin" / "colab",
pathlib.Path.home() / ".venvs" / "colab-cli" / "bin" / "colab",
):
if fallback.is_file():
return str(fallback)
return None
def _colab_python(colab_bin: str) -> str:
"""Returns the Python interpreter backing the ``colab`` console script."""
try:
first = (
pathlib.Path(colab_bin)
.read_text(encoding="utf-8", errors="ignore")
.splitlines()[0]
)
if first.startswith("#!"):
interp = first[2:].strip().split()[0]
if os.path.isfile(interp):
return interp
except OSError:
pass
sibling = pathlib.Path(colab_bin).resolve().parent / "python3"
return str(sibling) if sibling.is_file() else sys.executable
def _colab_oauth_helper(
colab_bin: str, auth_code: str | None = None
) -> tuple[bool, str]:
"""Starts or completes colab-cli OAuth2 without an interactive TTY."""
py = _colab_python(colab_bin)
helper = (
"import importlib.resources as res, json, os, sys\n"
"from colab_cli import auth as ca\n"
"from google_auth_oauthlib.flow import InstalledAppFlow\n"
"cfg_dir = os.path.dirname(ca.TOKEN_CONFIG_PATH)\n"
"os.makedirs(cfg_dir, exist_ok=True)\n"
"pending = os.path.join(cfg_dir, 'pending_oauth.json')\n"
"cfg_res = res.files('colab_cli').joinpath('oauth_config.json')\n"
"client_cfg = json.loads(cfg_res.read_text())\n"
"flow = InstalledAppFlow.from_client_config(client_cfg, "
"ca.PUBLIC_SCOPES)\n"
"flow.redirect_uri = ca.REMOTE_REDIRECT_URI\n"
f"code = {auth_code!r}\n"
"if code:\n"
" if os.path.exists(pending):\n"
" data = json.loads(open(pending).read())\n"
" flow.code_verifier = data.get('code_verifier')\n"
" flow.fetch_token(code=code.strip())\n"
" open(ca.TOKEN_CONFIG_PATH, 'w').write(flow.credentials.to_json())\n"
" if os.path.exists(pending):\n"
" os.remove(pending)\n"
" print('OAUTH_OK')\n"
"else:\n"
" url, _ = flow.authorization_url(prompt='consent', "
"token_usage='remote')\n"
" open(pending, 'w').write(json.dumps({'code_verifier': "
"flow.code_verifier}))\n"
" print('OAUTH_URL=' + url)\n"
)
try:
p = subprocess.run(
[py, "-c", helper],
cwd=tempfile.gettempdir(),
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=30,
check=False,
)
except (OSError, subprocess.SubprocessError) as e:
return False, str(e)
if p.returncode != 0:
return False, (p.stderr or p.stdout or "").strip()
for ln in (p.stdout or "").splitlines():
if ln == "OAUTH_OK":
return True, ""
if ln.startswith("OAUTH_URL="):
return False, ln[len("OAUTH_URL=") :]
return False, (p.stdout or "").strip()
def _run_colab(
colab_bin: str,
auth: str | None,
subargs: list[str],
timeout: int = 120,
) -> subprocess.CompletedProcess[str]:
"""Runs ``colab [--auth MODE] <subargs>`` with a timeout."""
cmd = [colab_bin]
if auth:
cmd += ["--auth", auth]
cmd += subargs
return subprocess.run(
cmd,
cwd=tempfile.gettempdir(),
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
def _build_remote_probe_script(
remote_dir: str, pinned_release: str | None
) -> str:
"""Python snippet run via ``colab exec`` to prepare ``remote_dir``."""
all_dists = list(LITERT_PAIRS[0] + LITERT_PAIRS[1])
return (
"import importlib.metadata as md, json, os, pathlib, platform, sys\n"
f"remote_dir = {remote_dir!r}\n"
"os.makedirs(f'{remote_dir}/scripts', exist_ok=True)\n"
"os.makedirs(f'{remote_dir}/assets', exist_ok=True)\n"
"os.makedirs(f'{remote_dir}/out', exist_ok=True)\n"
"installed = {}\n"
f"for dist in {all_dists!r}:\n"
" try:\n"
" installed[dist] = md.version(dist)\n"
" except md.PackageNotFoundError:\n"
" pass\n"
"has_lib = False\n"
"try:\n"
" import ai_edge_litert_sdk_google_tensor as gt_sdk\n"
" libs = gt_sdk.path_to_sdk_libs()\n"
f" has_lib = bool(libs and (pathlib.Path(libs) / {COMPILER_LIB_NAME!r})"
".is_file())\n"
"except Exception:\n"
" has_lib = False\n"
"info = {\n"
" 'host': f'{sys.platform}/{platform.machine()}',\n"
" 'python': platform.python_version(),\n"
" 'installed': installed,\n"
" 'has_compiler_lib': has_lib,\n"
f" 'pinned': {pinned_release!r},\n"
"}\n"
f"print({COLAB_PROBE_MARKER!r} + json.dumps(info))\n"
)
def _build_remote_compile_script(
remote_dir: str,
remote_model: str,
output_name: str,
args: argparse.Namespace,
remote_extra_options: str | None,
needs_sdk_install: bool,
remote_tarball: str | None,
sdk_url: str | None,
pinned_release: str | None,
) -> str:
"""Python script executed on the Colab VM to install the SDK and compile."""
remote_argv = [
f"{remote_dir}/scripts/compile_model.py",
remote_model,
"--target",
args.target,
"--output-dir",
f"{remote_dir}/out",
"--output-name",
output_name,
"--overwrite",
]
if args.truncation_type != "auto":
remote_argv += ["--truncation-type", args.truncation_type]
if args.sharding_intensity:
remote_argv += ["--sharding-intensity", args.sharding_intensity]
for flag, enabled in (
("--int64-to-int32", args.int64_to_int32),
("--large-model-support", args.large_model_support),
("--enable-4bit", args.enable_4bit),
("--keep-going", args.keep_going),
("--no-report-file", args.no_report_file),
("--force", args.force),
):
if enabled:
remote_argv.append(flag)
if remote_extra_options:
remote_argv += ["--extra-options-path", remote_extra_options]
release_spec = f"=={pinned_release}" if pinned_release else ""
pkgs = [
f"ai-edge-litert{release_spec}",
f"ai-edge-litert-sdk-google-tensor{release_spec}",
]
return (
"import ctypes, glob, os, subprocess, sys\n"
f"for first_part in sorted(glob.glob({remote_dir!r} + '/*.part000')):\n"
" target = first_part[:-len('.part000')]\n"
" parts = sorted(glob.glob(target + '.part*'))\n"
" with open(target, 'wb') as out_fh:\n"
" for part in parts:\n"
" with open(part, 'rb') as in_fh:\n"
" out_fh.write(in_fh.read())\n"
" os.remove(part)\n"
"def _ensure_libcxx():\n"
" try:\n"
" ctypes.CDLL('libc++.so.1')\n"
" return\n"
" except OSError:\n"
" pass\n"
" print('Installing libc++ runtime on Colab VM ...', flush=True)\n"
" subprocess.run(['apt-get', 'update', '-qq'], check=False)\n"
" r = subprocess.run(\n"
" ['apt-get', 'install', '-y', '-qq', 'libc++1', 'libc++abi1'],\n"
" check=False,\n"
" )\n"
" if r.returncode != 0:\n"
" subprocess.run(\n"
" ['apt-get', 'install', '-y', '-qq', 'libc++-18-dev',\n"
" 'libc++abi-18-dev'],\n"
" check=False,\n"
" )\n"
"_ensure_libcxx()\n"
f"if {needs_sdk_install!r}:\n"
" env = os.environ.copy()\n"
f" if {remote_tarball!r}:\n"
f" env['GOOGLE_TENSOR_SDK_BETA'] = {remote_tarball!r}\n"
f" elif {sdk_url!r}:\n"
f" env['GOOGLE_TENSOR_ML_SDK_URL'] = {sdk_url!r}\n"
f" pkgs = {pkgs!r}\n"
" print('Installing ' + ' '.join(pkgs) + ' on Colab VM ...', "
"flush=True)\n"
" pip_cmd = [\n"
" sys.executable, '-m', 'pip', 'install', '--no-cache-dir',\n"
" '--force-reinstall', *pkgs,\n"
" ]\n"
" p = subprocess.run(pip_cmd, env=env, text=True, "
"capture_output=True)\n"
" if p.returncode != 0:\n"
" sys.stdout.write(p.stdout or '')\n"
" sys.stderr.write(p.stderr or '')\n"
f" print({COLAB_EXIT_MARKER!r} + '5', flush=True)\n"
" raise SystemExit(0)\n"
f"cmd = [sys.executable, *{remote_argv!r}]\n"
"p = subprocess.run(cmd, text=True, capture_output=True)\n"
"if p.stdout:\n"
" sys.stdout.write(p.stdout)\n"
"if p.stderr:\n"
" sys.stderr.write(p.stderr)\n"
f"out_file = {f'{remote_dir}/out/{output_name}'!r}\n"
"chunk_max = 20 * 1024 * 1024\n"
"if p.returncode == 0 and os.path.isfile(out_file):\n"
" sz = os.path.getsize(out_file)\n"
" if sz > chunk_max:\n"
" n_parts = (sz + chunk_max - 1) // chunk_max\n"
" with open(out_file, 'rb') as fh:\n"
" for idx in range(n_parts):\n"
" with open(f'{out_file}.part{idx:03d}', 'wb') as pf:\n"
" pf.write(fh.read(chunk_max))\n"
" print('LITERT_COLAB_OUT_PARTS=' + str(n_parts), flush=True)\n"
f"print({COLAB_EXIT_MARKER!r} + str(p.returncode), flush=True)\n"
)
def _resolve_sdk_input(
raw_path: pathlib.Path,
) -> tuple[str | None, pathlib.Path | None]:
"""Resolves --sdk-tarball (archive, unpacked SDK dir, or compiler .so)."""
if not raw_path.exists():
return None, None
if raw_path.is_file():
lower = raw_path.name.lower()
if lower.endswith((".tar.gz", ".tgz", ".tar", ".zip")):
return "archive", raw_path
with raw_path.open("rb") as fh:
magic = fh.read(4)
if magic != b"\x7fELF" and raw_path.name != COMPILER_LIB_NAME:
return "archive", raw_path
sdk_dir = raw_path.parent
else:
sdk_dir = raw_path
if (
not (sdk_dir / COMPILER_LIB_NAME).is_file()
and (sdk_dir / "google_tensor_ml_sdk" / COMPILER_LIB_NAME).is_file()
):
sdk_dir = sdk_dir / "google_tensor_ml_sdk"
for parent in (sdk_dir.parent, sdk_dir.parent.parent):
sibling = parent / "litert_plugin_compiler.tar.gz"
if sibling.is_file():
print(f"NOTE: using sibling SDK archive {sibling} for {raw_path}.")
return "archive", sibling
if (sdk_dir / COMPILER_LIB_NAME).is_file() and (
sdk_dir / "third_party"
).is_dir():
return "dir", sdk_dir
return "incomplete", sdk_dir
def run_colab_compile(
args: argparse.Namespace,
model: pathlib.Path,
output_dir: pathlib.Path,
output_name: str,
output_path: pathlib.Path,
report_path: pathlib.Path,
pinned_release: str | None,
plan: dict[str, object],
) -> int:
"""Offloads compilation to a Google Colab Linux x86_64 VM via colab CLI.
Args:
args: Parsed command-line arguments.
model: Resolved path to the input .tflite file.
output_dir: Local directory where the compiled artifact will be written.
output_name: Filename for the compiled .tflite model.
output_path: Full local path for the compiled .tflite model.
report_path: Full local path for the .compile.json sidecar.
pinned_release: Pinned LiteRT release string from versions.json, or None.
plan: Dictionary summarizing the compile plan.
Returns:
Process exit code (0 on success, non-zero on failure).
"""
colab_bin = _resolve_colab_bin(args.colab_bin)
if not colab_bin:
print(
"ERROR: google-colab-cli ('colab') not found on PATH.\n"
+ colab_install_hint(pinned_release),
file=sys.stderr,
)
return 5
sdk_tarball_str = args.sdk_tarball or os.environ.get("GOOGLE_TENSOR_SDK_BETA")
sdk_url = args.sdk_url or os.environ.get("GOOGLE_TENSOR_ML_SDK_URL")
sdk_kind = None
sdk_tarball = None
if sdk_tarball_str:
raw_sdk = pathlib.Path(sdk_tarball_str).expanduser().resolve()
sdk_kind, sdk_tarball = _resolve_sdk_input(raw_sdk)
if sdk_kind is None:
print(
f"ERROR: Google Tensor SDK beta file not found: {raw_sdk}\n"
+ colab_install_hint(pinned_release),
file=sys.stderr,
)
return 5
if sdk_kind == "incomplete":
print(
f"ERROR: {raw_sdk} is a standalone {COMPILER_LIB_NAME} without the "
"SDK's third_party/ toolchain directory. Pass the full "
"litert_plugin_compiler.tar.gz archive (or the unpacked "
"google_tensor_ml_sdk/ directory containing both "
f"{COMPILER_LIB_NAME} and third_party/).\n"
+ colab_install_hint(pinned_release),
file=sys.stderr,
)
return 5
elif not sdk_url and not args.colab_session:
print(
"ERROR: Google Tensor SDK Beta tarball not specified (pass "
"--sdk-tarball /abs/path/litert_plugin_compiler.tar.gz or export "
"GOOGLE_TENSOR_SDK_BETA).\n"
+ colab_install_hint(pinned_release),
file=sys.stderr,
)
return 5
session_name = args.colab_session or f"litert-gt-{os.getpid()}"
if args.colab_auth_code:
ok, msg = _colab_oauth_helper(colab_bin, args.colab_auth_code)
if not ok:
print(
f"ERROR: failed to exchange --colab-auth-code: {msg}",
file=sys.stderr,
)
return 5
print("Saved Google Colab OAuth token.")
try:
sessions_proc = _run_colab(
colab_bin, args.colab_auth, ["sessions"], timeout=60
)
except (OSError, subprocess.SubprocessError) as e:
print(
f"ERROR: failed to run '{colab_bin} sessions': {e}\n"
+ colab_install_hint(pinned_release),
file=sys.stderr,
)
return 5
if sessions_proc.returncode != 0:
detail = (
(sessions_proc.stderr or "") + "\n" + (sessions_proc.stdout or "")
).strip()
if args.colab_auth != "adc" and (
"To authorize colab-cli" in detail
or "Enter the authorization code" in detail
or "EOFError" in detail
):
_, auth_url = _colab_oauth_helper(colab_bin, None)
if auth_url.startswith("http"):
print(
"ERROR: Google Colab CLI needs one-time OAuth authorization.\n"
"Ask the user to open this URL in their browser and paste the "
"authorization code back in chat (no terminal command needed):\n\n"
f" {auth_url}\n\n"
"Then re-run this exact command with: "
"--colab-auth-code <CODE>",
file=sys.stderr,
)
return 5
print(
f"ERROR: 'colab sessions' failed (exit {sessions_proc.returncode}): "
f"{detail}\n"
+ colab_install_hint(pinned_release),
file=sys.stderr,
)
return 5
session_reused = bool(
args.colab_session
and re.search(
rf"(?:\[{re.escape(session_name)}\]|\b{re.escape(session_name)}\b)",
sessions_proc.stdout or "",
)
)
if not session_reused and sdk_tarball is None and not sdk_url:
print(
f"ERROR: Colab session '{session_name}' is not active and no Beta "
"SDK tarball was provided (pass --sdk-tarball FILE or export "
"GOOGLE_TENSOR_SDK_BETA).\n"
+ colab_install_hint(pinned_release),
file=sys.stderr,
)
return 5
scratch = pathlib.Path(tempfile.mkdtemp(prefix="litert_gt_colab_"))
remote_dir = f"/content/litert_gt_{int(time.time())}_{os.getpid()}"
created_session = False
remote_dir_created = False
def _terminate(signum, unused_frame):
raise SystemExit(128 + signum)
prev_handlers = {}
for sig_name in ("SIGINT", "SIGTERM", "SIGHUP"):
sig = getattr(signal, sig_name, None)
if sig is not None:
try:
prev_handlers[sig] = signal.signal(sig, _terminate)
except (OSError, ValueError):
pass
try:
if session_reused:
print(f"Reusing active Google Colab session '{session_name}'.")
else:
new_cmd = ["new", "-s", session_name]
if args.colab_high_mem:
new_cmd.append("--high-mem")
print(
"Provisioning Google Colab Linux x86_64 VM "
f"(session '{session_name}') ..."
)
new_proc = _run_colab(colab_bin, args.colab_auth, new_cmd, timeout=180)
if new_proc.returncode != 0:
detail = (new_proc.stderr or new_proc.stdout or "").strip()
print(
f"ERROR: 'colab new -s {session_name}' failed "
f"(exit {new_proc.returncode}): {detail}",
file=sys.stderr,
)
return 5
created_session = True
probe_file = scratch / "probe.py"
probe_file.write_text(
_build_remote_probe_script(remote_dir, pinned_release),
encoding="utf-8",
)
probe_proc = _run_colab(
colab_bin,
args.colab_auth,
["exec", "-s", session_name, "--timeout", "60", "-f", str(probe_file)],
timeout=120,
)
if probe_proc.returncode != 0:
detail = (probe_proc.stderr or probe_proc.stdout or "").strip()
print(
f"ERROR: failed to initialize remote Colab directory {remote_dir} "
f"(exit {probe_proc.returncode}): {detail}",
file=sys.stderr,
)
return 5
remote_dir_created = True
probe = {}
for ln in (probe_proc.stdout or "").splitlines():
if ln.startswith(COLAB_PROBE_MARKER):
try:
probe = json.loads(ln[len(COLAB_PROBE_MARKER) :])
except ValueError:
probe = {}
remote_host = probe.get("host", "unknown")
if probe and remote_host != "linux/x86_64":
print(
f"ERROR: remote Colab runtime is {remote_host}, expected "
"linux/x86_64.",
file=sys.stderr,
)
return 4
installed_remote = probe.get("installed") or {}
already_installed = bool(
probe.get("has_compiler_lib")
and (
not pinned_release
or (
installed_remote.get("ai-edge-litert") == pinned_release
and installed_remote.get("ai-edge-litert-sdk-google-tensor")
== pinned_release
)
)
)
needs_sdk_install = not already_installed
if needs_sdk_install and sdk_tarball is None and not sdk_url:
print(
f"ERROR: Colab session '{session_name}' does not have the Google "
"Tensor compiler installed, and no Beta SDK tarball was provided. "
"Pass --sdk-tarball /abs/path/litert_plugin_compiler.tar.gz "
"(or export GOOGLE_TENSOR_SDK_BETA).",
file=sys.stderr,
)
return 5
print(
f"Colab VM ready ({remote_host}, Python {probe.get('python', '?')}); "
f"staging files in {remote_dir} ..."
)
uploads = [
(
pathlib.Path(__file__).resolve(),
f"{remote_dir}/scripts/compile_model.py",
),
]
if VERSIONS_FILE.is_file():
uploads.append((VERSIONS_FILE, f"{remote_dir}/assets/versions.json"))
remote_model = f"{remote_dir}/{_safe_name(model.name)}"
uploads.append((model, remote_model))
remote_extra_options = None
if args.extra_options_path:
extra_path = pathlib.Path(args.extra_options_path).expanduser().resolve()
remote_extra_options = f"{remote_dir}/extra_{_safe_name(extra_path.name)}"
uploads.append((extra_path, remote_extra_options))
remote_tarball = None
if needs_sdk_install and sdk_tarball is not None:
if sdk_kind == "dir":
packed = scratch / "litert_plugin_compiler.tar.gz"
print(
f"Packing unpacked SDK directory {sdk_tarball} into "
f"{packed.name} ..."
)
with tarfile.open(packed, "w:gz") as tf:
tf.add(sdk_tarball, arcname="google_tensor_ml_sdk")
sdk_tarball = packed
remote_tarball = f"{remote_dir}/{_safe_name(sdk_tarball.name)}"
print(
f"Uploading Beta SDK tarball {sdk_tarball.name} "
f"({fmt_size(sdk_tarball.stat().st_size)}) to Colab ..."
)
uploads.append((sdk_tarball, remote_tarball))
elif not needs_sdk_install:
print(
f"Reusing pre-installed LiteRT {pinned_release or 'packages'} on "
f"Colab session '{session_name}'."
)
chunk_max = 20 * 1024 * 1024
expanded_uploads: list[tuple[pathlib.Path, str]] = []
for local_src, remote_dst in uploads:
size = local_src.stat().st_size
if size <= chunk_max:
expanded_uploads.append((local_src, remote_dst))
else:
num_parts = (size + chunk_max - 1) // chunk_max
print(
f"Splitting {local_src.name} ({fmt_size(size)}) into {num_parts} "
"parts for Colab upload ..."
)
with local_src.open("rb") as fh:
for idx in range(num_parts):
part_path = scratch / f"{_safe_name(local_src.name)}.part{idx:03d}"
part_path.write_bytes(fh.read(chunk_max))
expanded_uploads.append((part_path, f"{remote_dst}.part{idx:03d}"))
for local_src, remote_dst in expanded_uploads:
up_proc = _run_colab(
colab_bin,
args.colab_auth,
["upload", "-s", session_name, str(local_src), remote_dst],
timeout=max(300, args.colab_timeout),
)
if up_proc.returncode != 0:
detail = (up_proc.stderr or up_proc.stdout or "").strip()
print(
f"ERROR: 'colab upload' failed for {local_src} -> {remote_dst} "
f"(exit {up_proc.returncode}): {detail}",
file=sys.stderr,
)
return 5
runner_file = scratch / "run_compile.py"
runner_file.write_text(
_build_remote_compile_script(
remote_dir=remote_dir,
remote_model=remote_model,
output_name=output_name,
args=args,
remote_extra_options=remote_extra_options,
needs_sdk_install=needs_sdk_install,
remote_tarball=remote_tarball,
sdk_url=sdk_url,
pinned_release=pinned_release,
),
encoding="utf-8",
)
print(f"Running AOT compilation on Colab session '{session_name}' ...")
try:
exec_proc = _run_colab(
colab_bin,
args.colab_auth,
[
"exec",
"-s",
session_name,
"--timeout",
str(args.colab_timeout),
"-f",
str(runner_file),
],
timeout=args.colab_timeout + 60,
)
except subprocess.TimeoutExpired:
print(
"ERROR: remote Colab compilation timed out after "
f"--colab-timeout {args.colab_timeout}s.",
file=sys.stderr,
)
return 6
remote_rc = None
out_parts = 0
out_lines = []
for ln in (exec_proc.stdout or "").splitlines():
if ln.startswith(COLAB_EXIT_MARKER):
try:
remote_rc = int(ln[len(COLAB_EXIT_MARKER) :].strip())
except ValueError:
remote_rc = 6
elif ln.startswith("LITERT_COLAB_OUT_PARTS="):
try:
out_parts = int(ln[len("LITERT_COLAB_OUT_PARTS=") :].strip())
except ValueError:
out_parts = 0
else:
out_lines.append(ln)
if out_lines:
print("\n".join(out_lines))
if exec_proc.stderr:
sys.stderr.write(exec_proc.stderr)
if exec_proc.returncode != 0 and remote_rc is None:
print(
f"ERROR: 'colab exec' failed (exit {exec_proc.returncode}).",
file=sys.stderr,
)
return 6
if remote_rc is None:
remote_rc = 6
if remote_rc != 0:
return remote_rc
output_dir.mkdir(parents=True, exist_ok=True)
remote_out_model = f"{remote_dir}/out/{output_name}"
if out_parts > 0:
print(f"Downloading compiled model from Colab in {out_parts} parts ...")
with output_path.open("wb") as out_fh:
for idx in range(out_parts):
part_local = scratch / f"dl.part{idx:03d}"
dl_proc = _run_colab(
colab_bin,
args.colab_auth,
[
"download",
"-s",
session_name,
f"{remote_out_model}.part{idx:03d}",
str(part_local),
],
timeout=max(300, args.colab_timeout),
)
if dl_proc.returncode != 0 or not part_local.is_file():
detail = (dl_proc.stderr or dl_proc.stdout or "").strip()
print(
f"ERROR: failed to download part {idx + 1}/{out_parts} of "
f"{remote_out_model} (exit {dl_proc.returncode}): {detail}",
file=sys.stderr,
)
return 7
out_fh.write(part_local.read_bytes())
part_local.unlink(missing_ok=True)
else:
dl_proc = _run_colab(
colab_bin,
args.colab_auth,
["download", "-s", session_name, remote_out_model, str(output_path)],
timeout=max(300, args.colab_timeout),
)
if dl_proc.returncode != 0 or not output_path.is_file():
detail = (dl_proc.stderr or dl_proc.stdout or "").strip()
print(
f"ERROR: failed to download compiled model {remote_out_model} "
f"(exit {dl_proc.returncode}): {detail}",
file=sys.stderr,
)
return 7
out_info = _inspect(output_path)
if not (out_info["compiled"] and args.target in out_info["soc_models"]):
print(
f"ERROR: {output_path} does not carry the expected Google Tensor "
f"stamp for {args.target} (found {out_info['soc_models']}).",
file=sys.stderr,
)
return 7
summary = None
if not args.no_report_file:
remote_out_report = f"{remote_out_model}.compile.json"
dl_rep = _run_colab(
colab_bin,
args.colab_auth,
["download", "-s", session_name, remote_out_report, str(report_path)],
timeout=120,
)
if dl_rep.returncode != 0 or not report_path.is_file():
detail = (dl_rep.stderr or dl_rep.stdout or "").strip()
print(
f"ERROR: failed to download compile sidecar {remote_out_report} "
f"(exit {dl_rep.returncode}): {detail}",
file=sys.stderr,
)
return 7
try:
summary = json.loads(report_path.read_text(encoding="utf-8"))
except (OSError, ValueError) as e:
print(
f"ERROR: invalid downloaded sidecar {report_path}: {e}",
file=sys.stderr,
)
return 7
expected_sha = summary.get("output_sha256")
actual_sha = sha256_of(output_path)
if expected_sha and actual_sha != expected_sha:
print(
f"ERROR: SHA-256 mismatch on downloaded {output_path} "
f"(expected {expected_sha}, got {actual_sha}).",
file=sys.stderr,
)
return 7
summary["input"] = str(model)
summary["output"] = str(output_path)
summary["compiled_via"] = "colab"
summary["colab_session"] = session_name
summary["local_host"] = plan["host"]
report_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")
print(
f"Compiled model downloaded to {output_path} "
f"({fmt_size(out_info['size_bytes'])})."
)
if not args.no_report_file:
print(f"Compile report written to {report_path}")
if args.json and summary is not None:
print(json.dumps(summary))
return 0
except KeyboardInterrupt:
print(
"\nInterrupted (Ctrl-C); cleaning up Google Colab resources ...",
file=sys.stderr,
)
return 130
finally:
for sig, prev in prev_handlers.items():
try:
signal.signal(sig, prev)
except (OSError, ValueError):
pass
if created_session and not args.keep_colab_session:
try:
_run_colab(
colab_bin, args.colab_auth, ["stop", "-s", session_name], timeout=60
)
print(f"Stopped Google Colab session '{session_name}'.")
except Exception as e: # pylint: disable=broad-exception-caught
print(
f"WARNING: failed to stop Colab session '{session_name}': {e}. "
f"Run: colab stop -s {session_name}",
file=sys.stderr,
)
elif remote_dir_created:
try:
cleanup_file = scratch / "cleanup.py"
cleanup_file.write_text(
f"import shutil\nshutil.rmtree({remote_dir!r},"
" ignore_errors=True)\n",
encoding="utf-8",
)
_run_colab(
colab_bin,
args.colab_auth,
[
"exec",
"-s",
session_name,
"--timeout",
"30",
"-f",
str(cleanup_file),
],
timeout=60,
)
except Exception: # pylint: disable=broad-exception-caught
pass
print(
f"Kept Google Colab session '{session_name}' active. Stop it when "
f"done with: colab stop -s {session_name}"
)
shutil.rmtree(scratch, ignore_errors=True)
def main(argv=None) -> int:
args = parse_args(argv)
if args.print_install:
return print_install(colab=args.colab)
try: # progress visible live when an agent captures stdout through a pipe
sys.stdout.reconfigure(line_buffering=True)
except (AttributeError, ValueError):
pass
if args.colab_timeout <= 0:
print("ERROR: --colab-timeout must be positive.", file=sys.stderr)
return 2
if args.extra_options_path:
extra_opt_file = pathlib.Path(args.extra_options_path).expanduser()
if not extra_opt_file.is_file():
print(
f"ERROR: --extra-options-path not found: {extra_opt_file}",
file=sys.stderr,
)
return 2
model = pathlib.Path(args.model).expanduser().resolve()
if not model.is_file():
print(f"ERROR: model not found: {model}", file=sys.stderr)
return 2
info = _inspect(model)
if not info["is_tflite"]:
print(f"ERROR: {model} is not a .tflite flatbuffer.", file=sys.stderr)
return 2
if info["compiled"] and not args.force:
print(
f"ERROR: {model} is already compiled for "
f"{', '.join(info['soc_models']) or 'an NPU'}. The compiler cannot "
"recompile a compiled model; compile the ORIGINAL (uncompiled) "
"export instead.",
file=sys.stderr,
)
return 3
if info["legacy_ops"] and not args.force:
print(
f"ERROR: {model} was compiled by another toolchain: it holds an Edge "
f"TPU custom op ({', '.join(info['legacy_ops'])}) instead of TFLite "
"ops, so the compiler finds nothing to compile. Compile the ORIGINAL "
"model it was made from instead (check_compiled.py exits 4 for such "
"files).",
file=sys.stderr,
)
return 3
output_dir = (
pathlib.Path(args.output_dir).expanduser().resolve()
if args.output_dir
else model.parent / "compiled"
)
output_name = args.output_name or f"{model.stem}_Google_{args.target}.tflite"
output_path = output_dir / output_name
report_path = output_path.with_name(output_path.name + ".compile.json")
backend_kwargs = build_backend_kwargs(args)
# The flags exactly as given (minus paths), for the sidecar and reports.
cli_flags = [f"--target {args.target}"]
if args.truncation_type != "auto":
cli_flags.append(f"--truncation-type {args.truncation_type}")
if args.sharding_intensity:
cli_flags.append(f"--sharding-intensity {args.sharding_intensity}")
for name in (
"int64_to_int32",
"large_model_support",
"enable_4bit",
"keep_going",
):
if getattr(args, name):
cli_flags.append("--" + name.replace("_", "-"))
if args.extra_options_path:
cli_flags.append("--extra-options-path <file>")
host_ok = sys.platform == "linux" and platform.machine() == "x86_64"
output_exists = output_path.exists()
try:
pinned_release = load_versions()["pip_release"]
except ValueError as e:
pinned_release = None
print(
f"WARNING: {e}; the installed LiteRT versions will not be compared "
"with the skill's pin.",
file=sys.stderr,
)
plan = {
"input": str(model),
"input_size_bytes": info["size_bytes"],
"target": args.target,
"output": str(output_path),
"output_exists": output_exists,
"report_file": None if args.no_report_file else str(report_path),
"keep_going": args.keep_going,
"backend_kwargs": backend_kwargs,
"host": f"{sys.platform}/{platform.machine()}",
"host_supported": host_ok or args.colab,
"pinned_pip_release": pinned_release,
}
if args.colab:
plan["execution"] = "colab"
plan["colab_session"] = args.colab_session or f"litert-gt-{os.getpid()}"
plan["colab_high_mem"] = args.colab_high_mem
plan["keep_colab_session"] = args.keep_colab_session
print("Compile plan:")
print(json.dumps(plan, indent=2))
if output_exists and not args.overwrite:
verb = "would stop" if args.dry_run else "stopping"
print(
f"{'NOTE' if args.dry_run else 'ERROR'}: output already exists: "
f"{output_path} - {verb} so it is not overwritten. Check it with "
"scripts/check_compiled.py and reuse it, or pass --output-name NAME, "
"or --overwrite.",
file=sys.stdout if args.dry_run else sys.stderr,
)
if not args.dry_run:
return 2
if args.dry_run:
print("--dry-run: nothing compiled.")
return 0 if (host_ok or args.colab) else 4
if args.colab:
return run_colab_compile(
args,
model,
output_dir,
output_name,
output_path,
report_path,
pinned_release,
plan,
)
if not host_ok:
print(
"ERROR: the Google Tensor compiler plugin only runs locally on Linux "
f"x86_64 (this host is {plan['host']}). Either pass --colab (with "
"google-colab-cli and --sdk-tarball /abs/path/litert_plugin_compiler"
".tar.gz) to compile on a remote Google Colab Linux x86_64 VM, or run "
"the compile step on a Linux x86_64 machine; benchmarking can still "
"be done from this host.",
file=sys.stderr,
)
return 4
# Progress bars render as hundreds of '\r' fragments in captured logs.
os.environ.setdefault("TQDM_DISABLE", "1")
# Must be set before importing ai_edge_litert.aot (stable package).
os.environ.setdefault("GOOGLE_TENSOR_BACKEND_ENABLED", "1")
try:
from ai_edge_litert.aot import aot_compile as aot_lib # pylint: disable=g-import-not-at-top
from ai_edge_litert.aot.vendors.google_tensor import target as gt_target # pylint: disable=g-import-not-at-top
except ImportError as e:
print(
f"ERROR: cannot import the LiteRT AOT API ({e!r}).\n"
f"{install_hint(pinned_release)}",
file=sys.stderr,
)
return 5
# Locate the native compiler library. The backend looks in the SDK package's
# data/ directory first and falls back to $GOOGLE_TENSOR_COMPILER_LIB only
# when the SDK package is not importable, so mirror that order here.
sdk_libs = None
try:
import ai_edge_litert_sdk_google_tensor as gt_sdk # pylint: disable=g-import-not-at-top
sdk_libs = gt_sdk.path_to_sdk_libs() # None when data/ was never populated
sdk_source = (
f"package ai_edge_litert_sdk_google_tensor {gt_sdk.__version__}"
)
except ImportError:
sdk_source = "env GOOGLE_TENSOR_COMPILER_LIB"
if os.environ.get("GOOGLE_TENSOR_COMPILER_LIB"):
sdk_libs = pathlib.Path(os.environ["GOOGLE_TENSOR_COMPILER_LIB"])
except NotImplementedError as e: # raised on unsupported hosts
print(f"ERROR: {e}", file=sys.stderr)
return 4
sdk_dir = pathlib.Path(sdk_libs) if sdk_libs else None
found_libs = (
sorted(sdk_dir.glob("*.so*")) if sdk_dir and sdk_dir.is_dir() else []
)
if not found_libs:
where = (
f"{sdk_dir} has no shared libraries"
if sdk_dir
else "the SDK package has no data/ directory"
)
print(
f"ERROR: {COMPILER_LIB_NAME} not found ({sdk_source}: {where}).\n"
"The ai-edge-litert-sdk-google-tensor package only contains the "
"compiler when the Beta tarball was supplied at pip-install time.\n"
+ install_hint(pinned_release),
file=sys.stderr,
)
return 5
if not (sdk_dir / COMPILER_LIB_NAME).is_file():
print(
f"WARNING: {COMPILER_LIB_NAME} not found in {sdk_dir}; found "
f"{[p.name for p in found_libs]}. Continuing, the compiler adapter "
"will report whether it can load the library.",
file=sys.stderr,
)
print(f"Compiler library directory: {sdk_dir} ({sdk_source})")
installed = installed_litert_versions()
for level, message in version_warnings(installed, pinned_release):
print(
f"{level}: {message}",
file=sys.stderr if level == "WARNING" else sys.stdout,
)
target = gt_target.Target(gt_target.SocModel(args.target))
output_dir.mkdir(parents=True, exist_ok=True)
if args.keep_intermediates:
work_dir = output_dir / "_intermediates"
work_dir.mkdir(parents=True, exist_ok=True)
tmp = None
else:
tmp = tempfile.TemporaryDirectory(prefix="litert_gt_compile_")
work_dir = pathlib.Path(tmp.name)
print(f"Compiling {model.name} for {target!r} ...")
started = time.time()
try:
result = aot_lib.aot_compile(
str(model),
output_dir=str(work_dir),
target=target,
keep_going=args.keep_going,
**backend_kwargs,
)
except Exception as e: # pylint: disable=broad-exception-caught
message = str(e)
print(
f"ERROR: compilation raised {type(e).__name__}: {message}",
file=sys.stderr,
)
# aot_compile points at a log file ("See /tmp/xxx.error for details");
# surface its ERROR lines so the user does not have to open it.
error_lines = []
log_match = re.search(r"See (\S+\.error) for details", message)
if log_match and os.path.isfile(log_match.group(1)):
with open(log_match.group(1), encoding="utf-8", errors="replace") as fh:
error_lines = [ln.rstrip() for ln in fh if "ERROR" in ln]
if error_lines:
print("Compiler log errors:", file=sys.stderr)
for ln in error_lines[-15:]:
print(f" {ln}", file=sys.stderr)
if tmp:
tmp.cleanup()
if any(
COMPILER_LIB_NAME in ln and "cannot open" in ln for ln in error_lines
):
print(
f"The compiler plugin could not load {COMPILER_LIB_NAME}.\n"
+ install_hint(pinned_release),
file=sys.stderr,
)
return 5
if info["compiled"] or info["legacy_ops"]:
print(
"The input was already a compiled model (--force only skipped the "
"check): the compiler cannot recompile DISPATCH_OP partitions or "
"Edge TPU custom ops and typically fails with 'compiled_result or "
"num_byte_code is nullptr'. Compile the ORIGINAL (uncompiled) "
"export instead.",
file=sys.stderr,
)
return 6
print(
"See references/troubleshooting.md (e.g. retry with "
"--truncation-type half --sharding-intensity maximum).",
file=sys.stderr,
)
return 6
elapsed = time.time() - started
report = result.compilation_report()
print("\n===== Compilation report =====")
print(report)
print("==============================\n")
if result.failed_backends or not result.models_with_backend:
print("ERROR: no compiled model was produced.", file=sys.stderr)
for backend, err in result.failed_backends:
print(f" {backend.target_id}: {err}", file=sys.stderr)
if tmp:
tmp.cleanup()
return 6
_, compiled_model = result.models_with_backend[0]
compiled_model.save(output_path, export_only=True)
if tmp:
tmp.cleanup()
out_info = _inspect(output_path)
if not (out_info["compiled"] and args.target in out_info["soc_models"]):
print(
f"ERROR: {output_path} does not carry the expected Google Tensor "
f"stamp for {args.target} (found {out_info['soc_models']}).",
file=sys.stderr,
)
return 7
# Sum the per-subgraph "X / Y ops offloaded to Z partitions" lines.
partitions = [tuple(int(x) for x in m) for m in PARTITION_RE.findall(report)]
ops_offloaded = sum(p[0] for p in partitions) if partitions else None
ops_total = sum(p[1] for p in partitions) if partitions else None
compiler_lib = sdk_dir / COMPILER_LIB_NAME
summary = {
"status": "ok",
"compiled_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
"input": str(model),
"input_size_bytes": info["size_bytes"],
"input_sha256": sha256_of(model),
"output": str(output_path),
"output_size_bytes": out_info["size_bytes"],
"output_sha256": sha256_of(output_path),
"target": args.target,
"cli_flags": cli_flags,
"backend_kwargs": backend_kwargs,
"ops_offloaded": ops_offloaded,
"ops_total": ops_total,
"partitions": sum(p[2] for p in partitions) if partitions else None,
"fully_compiled": (ops_offloaded == ops_total) if partitions else None,
"compilation_report": report,
"packages": installed,
"pinned_pip_release": pinned_release,
"compiler_library_dir": str(sdk_dir),
# Identifies the Beta tarball's compiler build behind this artifact.
"compiler_library_sha256": (
sha256_of(compiler_lib) if compiler_lib.is_file() else None
),
"host": plan["host"],
"elapsed_seconds": round(elapsed, 1),
}
print(
f"Compiled model written to {output_path} "
f"({fmt_size(out_info['size_bytes'])}) in {elapsed:.0f}s."
)
if ops_total is not None:
if ops_offloaded == ops_total:
partial_note = ""
else:
partial_note = (
" - NOT fully compiled; a strict NPU benchmark will fail, see "
"--allow-cpu-fallback in benchmark_on_device.py"
)
print(
f"Ops offloaded to the TPU: {ops_offloaded} / {ops_total}"
+ partial_note
)
if not args.no_report_file:
report_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")
print(f"Compile report written to {report_path}")
if args.json:
print(json.dumps(summary))
return 0
if __name__ == "__main__":
sys.exit(main())
install_and_verify.py 28.0 KB
#!/usr/bin/env python3
# Copyright 2026 The Google AI Edge Authors. All Rights Reserved.
#
# 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.
"""Installs the user's app on a Pixel the way Google Play would.
It then checks that the model runs on the Google Tensor TPU.
For an Android (Gradle) app set up with package_ai_pack.py (SKILL.md steps 5
and 6). The script:
1. finds the app module, its device-targeting XML, the Android SDK, adb,
Java, Gradle (the project's ./gradlew) and bundletool;
2. reads the attached Pixel's SoC and picks its device group;
3. builds the app bundle (:<app module>:bundleDebug, or the bundle task of
--variant, e.g. bundleRelease or bundleFreeDebug);
4. runs bundletool build-apks --local-testing and install-apks for that
device group: what Google Play would install on this phone;
5. checks the installed splits and the Google Tensor dispatch library;
6. starts the app and waits for TensorModelLoader's LITERT_TENSOR_RESULT
log line ("path":"npu" or "cpu").
bundletool comes from --bundletool (a bundletool-all jar, or a folder of
jars), else bundletool-all-<bundletool_release>.jar from GitHub, cached in
~/.cache/litert-google-tensor/ (bundletool_release is in versions.json).
Local testing cannot update an installed app. If the app is installed, the
script stops (exit 7) unless --uninstall-first is passed. Uninstalling
deletes the app's data on the phone, so ask the user first. The app stays
installed afterwards. The script never signs for release or uploads.
Exit codes
----------
0 the model ran on the TPU, or on the CPU on a phone the app has no Google
Tensor build for; with --no-launch: installed
1 the app used the CPU on a phone it has a Google Tensor build for
2 bad arguments or environment (project, app module, SDK, adb, Java, Gradle,
device)
3 the Gradle build failed
4 bundletool failed (download, build-apks or install-apks)
6 no LITERT_TENSOR_RESULT line within --timeout (the app must call
TensorModelLoader.load(): open the screen that uses the model)
7 the app is already installed: rerun with --uninstall-first once the user
agrees
"""
from __future__ import annotations
import argparse
import datetime
import json
import os
import pathlib
import re
import shutil
import subprocess
import sys
import time
from typing import Any
import urllib.request
import xml.etree.ElementTree as ET
SKILL_DIR = pathlib.Path(__file__).resolve().parent.parent
VERSIONS_FILE = SKILL_DIR / "assets" / "versions.json"
CACHE_DIR = pathlib.Path.home() / ".cache" / "litert-google-tensor"
BUNDLETOOL_URL = ("https://github.com/google/bundletool/releases/download/"
"{v}/bundletool-all-{v}.jar")
BUNDLETOOL_MAIN = "com.android.tools.build.bundletool.BundleToolMain"
SETTINGS_FILES = ("settings.gradle.kts", "settings.gradle")
BUILD_FILES = ("build.gradle.kts", "build.gradle")
DTC_NS = "http://schemas.android.com/apk/config"
LOG_TAG = "LiteRtTensor"
RESULT_PREFIX = "LITERT_TENSOR_RESULT "
DISPATCH_LIB = "libLiteRtDispatch_GoogleTensor.so"
TENSOR_SOC_RE = re.compile(r"Tensor G\d+")
_COMMENT_RE = re.compile(
r"(\"(?:\\.|[^\"\\\n])*\"|'(?:\\.|[^'\\\n])*')|//[^\n]*|/\*.*?\*/", re.S
)
_INCLUDE_RE = re.compile(r"\binclude\s*\(([^)]*)\)|\binclude[ \t]+([^\n]+)")
_QUOTED_RE = re.compile(r"[\"'](:?[\w.\-:]+)[\"']")
_DTC_RE = re.compile(
r"\bdeviceTargetingConfig\b\s*(?:=|\.set\s*\()?\s*"
r"(?P<fn>rootProject\.file|project\.file|layout\.projectDirectory\.file|"
r"file)\s*\(\s*[\"'](?P<path>[^\"']+)[\"']"
)
_APP_PLUGIN_RE = re.compile(
r"com\.android\.application|android\.application(?![\w.])")
_APPLY_FALSE_RE = re.compile(r"[^\n]*?\bapply\s*\(?\s*false\b")
class VerifyError(Exception):
"""A failure with the exit code to return and a message naming the fix."""
def __init__(self, code: int, message: str):
super().__init__(message)
self.code = code
def parse_args(argv=None) -> argparse.Namespace:
"""Parses the command-line arguments (default: sys.argv[1:])."""
p = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--project", required=True,
help="Root of the app's Gradle project (the folder with "
"settings.gradle.kts).")
p.add_argument("--app-module",
help="Gradle path of the app module (default: the only "
"module that applies com.android.application).")
p.add_argument("--variant", default="debug",
help="Build variant to bundle: debug (default), release, or "
"a product-flavor variant such as freeDebug. bundletool "
"signs the APKs with the debug key for local testing.")
p.add_argument("--serial", help="adb serial (required if >1 device).")
p.add_argument("--gradle",
help="Gradle command, split on spaces, so it can carry "
"options such as -Pname=value (default: the project's "
"gradlew, else gradle on PATH).")
p.add_argument("--bundletool",
help="A bundletool-all jar, or a folder of bundletool jars "
"(default: cached download of bundletool_release).")
p.add_argument("--sdk", help="Android SDK folder (default: ANDROID_HOME, "
"ANDROID_SDK_ROOT, local.properties, ~/Android/Sdk).")
p.add_argument("--uninstall-first", action="store_true",
help="Uninstall an installed copy of the app first (deletes "
"its data on the phone: ask the user).")
p.add_argument("--no-launch", action="store_true",
help="Stop after installing; do not start the app.")
p.add_argument("--timeout", type=int, default=120,
help="Seconds to wait for the LITERT_TENSOR_RESULT line "
"(default 120).")
p.add_argument("--output-dir",
help="Where to write logs, results.json and report.md "
"(default ./litert_app_verify/<timestamp>).")
p.add_argument("--keep-apks", action="store_true",
help="Keep the .apks file bundletool built (it is large).")
p.add_argument("--dry-run", action="store_true",
help="Check the project, tools and phone and print the "
"plan; build and install nothing.")
p.add_argument("--json", action="store_true",
help="Print a JSON summary only.")
return p.parse_args(argv)
# --------------------------------------------------------------------------
# Project
# --------------------------------------------------------------------------
def _read(path: pathlib.Path) -> str:
try:
return path.read_text(encoding="utf-8", errors="replace")
except OSError:
return ""
def _strip(text: str) -> str:
return _COMMENT_RE.sub(lambda m: m.group(1) or "", text)
def applies_app_plugin(text: str) -> bool:
"""True if a build file applies the Android application plugin.
A root build file that only declares it (``... apply false``) does not.
Args:
text: Contents of the build file, with comments stripped.
Returns:
Whether the build file applies the plugin.
"""
return any(not _APPLY_FALSE_RE.match(text, m.end())
for m in _APP_PLUGIN_RE.finditer(text))
def find_project(raw: str) -> tuple[pathlib.Path, pathlib.Path]:
root = pathlib.Path(raw).expanduser().resolve()
for name in SETTINGS_FILES:
if (root / name).is_file():
return root, root / name
raise VerifyError(2, f"no settings.gradle.kts or settings.gradle in {root}: "
"pass the root folder of the app's Gradle project.")
def find_app_module(root: pathlib.Path, settings: pathlib.Path,
wanted: str | None) -> dict[str, Any]:
"""{dir, gradle_path, build_file, text} of the app module."""
paths = {":": root}
for m in _INCLUDE_RE.finditer(_strip(_read(settings))):
for path in _QUOTED_RE.findall(m.group(1) or m.group(2) or ""):
gradle_path = ":" + path.lstrip(":")
paths[gradle_path] = root.joinpath(*gradle_path[1:].split(":"))
modules = []
for gradle_path, folder in paths.items():
build = next((folder / n for n in BUILD_FILES if (folder / n).is_file()),
None)
if build:
modules.append({"dir": folder, "gradle_path": gradle_path,
"build_file": build, "text": _strip(_read(build))})
if wanted:
want = ":" + wanted.strip(":")
for module in modules:
if module["gradle_path"] == want:
return module
raise VerifyError(2, f"--app-module {wanted}: not an included module with "
f"a build file in {settings}.")
apps = [m for m in modules if applies_app_plugin(m["text"])]
if len(apps) != 1:
found = ", ".join(m["gradle_path"] for m in apps) or "none"
raise VerifyError(2, f"cannot tell the app module (modules applying "
f"com.android.application: {found}); pass --app-module.")
return apps[0]
def device_groups(app: dict[str, Any],
root: pathlib.Path) -> tuple[dict[str, Any], str | None]:
"""({"Tensor G5": group}, XML path) from the app's device-targeting XML."""
m = _DTC_RE.search(app["text"])
if not m:
return {}, None
path = pathlib.Path(m.group("path")).expanduser()
if not path.is_absolute():
path = (root if m.group("fn") == "rootProject.file"
else app["dir"]) / path
try:
tree = ET.parse(path).getroot()
except (OSError, ET.ParseError) as e:
raise VerifyError(2, f"cannot read the device-targeting XML {path}: {e}"
) from e
groups = {}
for group in tree.iter(f"{{{DTC_NS}}}device-group"):
socs = [(s.get("manufacturer"), s.get("model"))
for s in group.iter(f"{{{DTC_NS}}}system-on-chip")]
if len(socs) == 1 and socs[0][0] == "Google" and TENSOR_SOC_RE.fullmatch(
socs[0][1] or ""):
groups[socs[0][1]] = group.get("name")
return groups, str(path)
def bundle_task(gradle_path: str, variant: str) -> str:
"""Bundle task of a variant: (":app", "freeDebug") -> ":app:bundleFreeDebug".
The root project as the app module (":") gives ":bundleFreeDebug".
Args:
gradle_path: Gradle path of the app module, e.g. ":app".
variant: Build variant name, e.g. "debug" or "freeDebug".
Returns:
The Gradle path of the variant's bundle task.
"""
return f"{gradle_path.rstrip(':')}:bundle{variant[0].upper()}{variant[1:]}"
# --------------------------------------------------------------------------
# Tools
# --------------------------------------------------------------------------
def find_sdk(explicit: str | None, root: pathlib.Path) -> pathlib.Path | None:
local = re.search(r"(?m)^\s*sdk\.dir\s*=\s*(.+?)\s*$",
_read(root / "local.properties"))
candidates = [explicit, os.environ.get("ANDROID_HOME"),
os.environ.get("ANDROID_SDK_ROOT"),
local.group(1).replace("\\:", ":") if local else None,
str(pathlib.Path.home() / "Android" / "Sdk"),
str(pathlib.Path.home() / "Library" / "Android" / "sdk")]
for c in candidates:
if c and (pathlib.Path(c) / "platform-tools").is_dir():
return pathlib.Path(c)
return None
def find_aapt2(sdk: pathlib.Path | None) -> pathlib.Path | None:
"""aapt2 of the newest build-tools (bundletool jars without aapt2)."""
if not sdk:
return None
def version(path: pathlib.Path) -> list[int]:
return [int(x) if x.isdigit() else 0
for x in path.parent.name.replace("-", ".").split(".")]
found = sorted((sdk / "build-tools").glob("*/aapt2*"), key=version)
return found[-1] if found else None
def find_tools(args: argparse.Namespace, root: pathlib.Path) -> dict[str, Any]:
"""Finds the Android SDK, adb, Java, Gradle and aapt2.
Args:
args: Parsed command-line arguments.
root: Root folder of the app's Gradle project.
Returns:
{"sdk", "adb", "java", "gradle", "aapt2"}: the SDK folder (or None), the
adb and java paths, the Gradle command (a list) and aapt2 (or None).
Raises:
VerifyError: adb, java or Gradle is not found.
"""
sdk = find_sdk(args.sdk, root)
adb_path = shutil.which("adb") or (
str(sdk / "platform-tools" / "adb") if sdk else None)
java_home = os.environ.get("JAVA_HOME")
java = (str(pathlib.Path(java_home) / "bin" / "java") if java_home
else shutil.which("java"))
wrapper = root / ("gradlew.bat" if os.name == "nt" else "gradlew")
gradle = (args.gradle.split() if args.gradle else
[str(wrapper)] if wrapper.is_file() else
[shutil.which("gradle")] if shutil.which("gradle") else None)
missing = [name for name, value in (("adb", adb_path), ("java", java),
("Gradle", gradle)) if not value]
if missing:
raise VerifyError(
2, f"{', '.join(missing)} not found. Install the Android SDK "
"platform-tools (adb) and a JDK the project's Gradle supports (set "
"JAVA_HOME), and run from a project with ./gradlew (or pass "
"--gradle).")
return {"sdk": sdk, "adb": adb_path, "java": java, "gradle": gradle,
"aapt2": find_aapt2(sdk)}
def read_bundletool_release() -> str | None:
try:
value = json.loads(VERSIONS_FILE.read_text(encoding="utf-8")).get(
"bundletool_release")
except (OSError, ValueError):
return None
return value if isinstance(value, str) else None
def bundletool_command(args: argparse.Namespace, java: str,
dry_run: bool) -> tuple[list[str], str]:
"""(command prefix, where it comes from)."""
if args.bundletool:
path = pathlib.Path(args.bundletool).expanduser().resolve()
if path.is_dir():
return ([java, "-cp", str(path / "*"), BUNDLETOOL_MAIN],
f"jars in {path}")
if path.is_file():
return [java, "-jar", str(path)], str(path)
raise VerifyError(2, f"--bundletool {path} does not exist.")
release = read_bundletool_release()
if not release:
raise VerifyError(2, f"no bundletool_release in {VERSIONS_FILE}: restore "
"the file, or pass --bundletool.")
jar = CACHE_DIR / f"bundletool-all-{release}.jar"
url = BUNDLETOOL_URL.format(v=release)
if not jar.is_file() and not dry_run:
CACHE_DIR.mkdir(parents=True, exist_ok=True)
part = jar.with_suffix(".part")
try:
with urllib.request.urlopen(url, timeout=120) as response, open(
part, "wb") as out:
shutil.copyfileobj(response, out)
part.replace(jar)
except OSError as e:
part.unlink(missing_ok=True)
raise VerifyError(4, f"cannot download {url} ({e}). Download a "
"bundletool-all jar yourself and pass --bundletool."
) from e
return [java, "-jar", str(jar)], (
str(jar) if jar.is_file() else f"{url} (not downloaded yet)")
# --------------------------------------------------------------------------
# Commands
# --------------------------------------------------------------------------
def run(cmd: list[str], log: pathlib.Path, code: int, what: str,
cwd: pathlib.Path | None = None) -> str:
"""Runs ``cmd`` with its output in ``log``; raises VerifyError on failure."""
with open(log, "w", encoding="utf-8") as f:
proc = subprocess.run(cmd, cwd=cwd, stdout=f, stderr=subprocess.STDOUT,
check=False)
text = log.read_text(encoding="utf-8", errors="replace")
if proc.returncode != 0:
tail = "\n".join(text.splitlines()[-25:])
raise VerifyError(code, f"{what} failed (exit {proc.returncode}); log: "
f"{log}\n{tail}")
return text
def adb(tools: dict[str, Any], serial: str | None, *args: str,
timeout: int = 60, check: bool = True) -> str:
cmd = [tools["adb"]] + (["-s", serial] if serial else []) + list(args)
try:
proc = subprocess.run(cmd, capture_output=True, text=True,
timeout=timeout, check=False)
except (OSError, subprocess.TimeoutExpired) as e:
raise VerifyError(2, f"{' '.join(cmd)}: {e}") from e
if check and proc.returncode != 0:
raise VerifyError(2, f"{' '.join(cmd)} failed: {proc.stderr.strip()}")
return proc.stdout
def pick_device(tools: dict[str, Any], serial: str | None) -> str:
lines = adb(tools, None, "devices").splitlines()[1:]
devices = [l.split()[0] for l in lines if l.strip().endswith("device")]
if serial:
if serial not in devices:
raise VerifyError(2, f"device {serial} is not in `adb devices`.")
return serial
if len(devices) != 1:
raise VerifyError(2, f"need exactly one device, found "
f"{devices or 'none'}: connect the Pixel (USB "
"debugging on) or pass --serial.")
return devices[0]
def device_info(tools: dict[str, Any], serial: str) -> dict[str, Any]:
def prop(name: str) -> str:
return adb(tools, serial, "shell", "getprop", name).strip()
sdk = prop("ro.build.version.sdk")
return {"serial": serial, "model": prop("ro.product.model"),
"soc": prop("ro.soc.model"),
"sdk": int(sdk) if sdk.isdigit() else 0,
"build_id": prop("ro.build.id")}
def npu_reason(device: dict[str, Any]) -> str | None:
"""Why LiteRT will not use the Google Tensor NPU here, or None."""
if not TENSOR_SOC_RE.fullmatch(device["soc"]):
return f"not a Google Tensor phone (SoC {device['soc'] or 'unknown'})"
if device["sdk"] < 36:
return f"Android API {device['sdk']}; the NPU needs API 36 or newer"
if device["build_id"].startswith("BP2A"):
return f"build {device['build_id']} has no NPU support"
return None
def wait_for_result(tools: dict[str, Any], serial: str, package: str,
timeout: int) -> dict[str, Any] | None:
"""Polls logcat for the app's LITERT_TENSOR_RESULT line.
Args:
tools: The tools from find_tools().
serial: adb serial of the device.
package: Application id of the installed app.
timeout: Seconds to wait for the line.
Returns:
The JSON after the LITERT_TENSOR_RESULT prefix, or None on timeout.
"""
deadline = time.time() + timeout
hint_at = time.time() + 20
while time.time() < deadline:
time.sleep(2)
pid = adb(tools, serial, "shell", "pidof", package, check=False).strip()
if pid:
log = adb(tools, serial, "logcat", "-d", f"--pid={pid.split()[0]}",
"-s", f"{LOG_TAG}:I", check=False)
for line in log.splitlines():
if RESULT_PREFIX in line:
try:
return json.loads(line.split(RESULT_PREFIX, 1)[1])
except ValueError:
continue
if time.time() > hint_at:
print("Waiting for LITERT_TENSOR_RESULT. If the app loads the model "
"later (on a particular screen), open it on the phone now.",
flush=True)
hint_at = deadline
return None
# --------------------------------------------------------------------------
# Main
# --------------------------------------------------------------------------
def verify(args: argparse.Namespace) -> dict[str, Any]:
"""Builds and installs the app, starts it and waits for its result line.
With --dry-run it only checks the project, tools and phone and returns the
plan; with --no-launch it stops after installing.
Args:
args: Parsed command-line arguments.
Returns:
The plan and, unless --dry-run, the install and launch results; "status"
is "dry-run", "installed", "ran" or "no_result".
Raises:
VerifyError: A step failed; its code is the exit code to return.
"""
if not re.fullmatch(r"[A-Za-z][A-Za-z0-9]*", args.variant):
raise VerifyError(2, f"--variant {args.variant}: pass a build variant "
"name such as debug, release or freeDebug.")
root, settings = find_project(args.project)
app = find_app_module(root, settings, args.app_module)
groups, xml = device_groups(app, root)
tools = find_tools(args, root)
bundletool, bundletool_src = bundletool_command(args, tools["java"],
args.dry_run)
serial = pick_device(tools, args.serial)
device = device_info(tools, serial)
group = groups.get(device["soc"])
reason = npu_reason(device) or (
None if group else f"the app has no Google Tensor build for "
f"{device['soc']} (groups: {', '.join(groups.values()) or 'none'})")
task = bundle_task(app["gradle_path"], args.variant)
plan = {
"project": str(root),
"app_module": app["gradle_path"],
"device_targeting_config": xml,
"device": device,
"device_group": group,
"expect_npu": reason is None,
"npu_reason": reason,
"gradle": " ".join(tools["gradle"] + [task]),
"bundletool": bundletool_src,
"aapt2": str(tools["aapt2"]) if tools["aapt2"] else None,
}
if args.dry_run:
return dict(plan, status="dry-run")
out = pathlib.Path(args.output_dir or pathlib.Path.cwd() / "litert_app_verify"
/ datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
out = out.expanduser().resolve()
out.mkdir(parents=True, exist_ok=True)
print(f"Building {task} ...", flush=True)
run(tools["gradle"] + ["-p", str(root), "--console=plain", task],
out / "gradle.log", 3, "the Gradle build", cwd=root)
bundle_dir = app["dir"] / "build" / "outputs" / "bundle" / args.variant
aabs = sorted(bundle_dir.glob("*.aab"), key=lambda p: p.stat().st_mtime)
if not aabs:
raise VerifyError(3, f"the build wrote no .aab to {bundle_dir}. If the "
"app has product flavors, pass --variant with the "
"flavor (for example freeDebug).")
aab = aabs[-1]
package = run(bundletool + ["dump", "manifest", f"--bundle={aab}",
"--xpath=/manifest/@package"],
out / "bundletool_dump.log", 4, "bundletool dump").strip()
package = package.splitlines()[-1].strip() if package else ""
if not re.fullmatch(r"[\w.]+", package):
raise VerifyError(4, f"cannot read the application id from {aab}.")
installed = adb(tools, serial, "shell", "pm", "path", package,
check=False).strip()
if installed and not args.uninstall_first:
raise VerifyError(7, f"{package} is already installed on {serial}, and "
"local testing cannot update an installed app. Ask "
"the user, then rerun with --uninstall-first (it "
"deletes the app's data on the phone).")
apks = out / "app.apks"
print(f"bundletool build-apks --local-testing ({aab.name}) ...", flush=True)
run(bundletool + ["build-apks", f"--bundle={aab}", f"--output={apks}",
"--local-testing", "--overwrite"]
+ ([f"--aapt2={tools['aapt2']}"] if tools["aapt2"] else []),
out / "build_apks.log", 4, "bundletool build-apks")
if installed: # only now that the new APK set is ready
adb(tools, serial, "uninstall", package, check=False)
print(f"Installing for device group {group or '(default)'} ...", flush=True)
run(bundletool + ["install-apks", f"--apks={apks}", f"--device-id={serial}",
f"--adb={tools['adb']}"]
+ ([f"--device-groups={group}"] if group else []),
out / "install_apks.log", 4, "bundletool install-apks")
if not args.keep_apks:
apks.unlink(missing_ok=True)
splits = [line.split("/")[-1] for line in adb(
tools, serial, "shell", "pm", "path", package).split()]
dump = adb(tools, serial, "shell", "dumpsys", "package", package,
check=False)
lib_dir = re.search(r"legacyNativeLibraryDir=(\S+)", dump)
abi = re.search(r"primaryCpuAbi=(\S+)", dump)
dispatch = None
if lib_dir and abi and abi.group(1) != "null":
sub = {"arm64-v8a": "arm64", "armeabi-v7a": "arm"}.get(abi.group(1),
abi.group(1))
listing = adb(tools, serial, "shell", "ls", f"{lib_dir.group(1)}/{sub}",
check=False)
dispatch = DISPATCH_LIB in listing
result = dict(plan, package=package, aab=str(aab), splits=splits,
dispatch_library_installed=dispatch, output_dir=str(out))
if args.no_launch:
return dict(result, status="installed")
component = adb(tools, serial, "shell", "cmd", "package",
"resolve-activity", "--brief", "-c",
"android.intent.category.LAUNCHER", package,
check=False).strip().splitlines()
if component and "/" in component[-1]:
adb(tools, serial, "shell", "am", "start", "-W", "-n", component[-1])
else:
adb(tools, serial, "shell", "monkey", "-p", package, "-c",
"android.intent.category.LAUNCHER", "1")
loaded = wait_for_result(tools, serial, package, args.timeout)
return dict(result, status="ran" if loaded else "no_result",
loader=loaded)
def report_markdown(result: dict[str, Any]) -> str:
"""Formats a verify() result as the Markdown report (stdout, report.md)."""
device = result["device"]
lines = [
f"**Device:** {device['model']} ({device['soc']}, API {device['sdk']}, "
f"build {device['build_id']}); device group "
f"`{result['device_group'] or 'none'}`",
f"**App:** `{result.get('package', '?')}` from {result['app_module']} "
f"({result['project']})",
]
if result.get("splits"):
lines.append("**Installed:** " + ", ".join(result["splits"]))
lines.append("**Dispatch library on the phone:** " + {
True: "yes", False: "NO", None: "unknown"}[
result["dispatch_library_installed"]])
loader = result.get("loader")
if loader:
verdict = loader.get("path")
lines.append(f"**Result:** `\"path\":\"{verdict}\"`, load "
f"{loader.get('load_ms')} ms"
+ (f", npu_error: {loader['npu_error']}"
if loader.get("npu_error") else ""))
elif result["status"] == "no_result":
lines.append("**Result:** no LITERT_TENSOR_RESULT line")
if not result["expect_npu"]:
lines.append(f"**Expected path:** CPU ({result['npu_reason']})")
if result.get("output_dir"):
lines.append(f"**Logs:** {result['output_dir']}")
return "\n".join(lines)
def main(argv=None) -> int:
args = parse_args(argv)
try:
result = verify(args)
except VerifyError as e:
if args.json:
print(json.dumps({"status": "error", "exit_code": e.code,
"error": str(e)}, indent=2))
else:
print(f"ERROR: {e}", file=sys.stderr)
return e.code
except KeyboardInterrupt:
print("Interrupted.", file=sys.stderr)
return 130
loader = result.get("loader")
if result["status"] == "dry-run":
code = 0
elif result["status"] == "installed":
code = 0
elif not loader:
code = 6
elif loader.get("path") == "npu" or not result["expect_npu"]:
code = 0
else:
code = 1
result["exit_code"] = code
if result.get("output_dir"):
out = pathlib.Path(result["output_dir"])
(out / "results.json").write_text(json.dumps(result, indent=2) + "\n",
encoding="utf-8")
(out / "report.md").write_text(report_markdown(result) + "\n",
encoding="utf-8")
if args.json:
print(json.dumps(result, indent=2))
elif result["status"] == "dry-run":
print("Dry run: project, tools and phone checked; nothing built or "
"installed.")
for key in ("project", "app_module", "device_targeting_config",
"device_group", "expect_npu", "npu_reason", "gradle",
"bundletool", "aapt2"):
print(f" {key}: {result[key]}")
else:
print()
print(report_markdown(result))
if code == 1:
print("FAIL: the app used the CPU on a phone it has a Google Tensor "
"build for (see npu_error, and references/troubleshooting.md).")
elif code == 6:
print("No result line: the app must call TensorModelLoader.load(). "
"Open the screen that uses the model, or rerun with a longer "
"--timeout.")
return code
if __name__ == "__main__":
sys.exit(main())
package_ai_pack.py 143.7 KB
#!/usr/bin/env python3
# Copyright 2026 The Google AI Edge Authors. All Rights Reserved.
#
# 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.
"""Packages Google Tensor-compiled .tflite builds for an Android (Gradle) app.
Turns builds made by compile_model.py (and ideally checked with
benchmark_on_device.py) into everything a Gradle app needs to ship them with
Google Play for On-device AI:
* a Google Play AI pack written by LiteRT's own exporter,
``ai_edge_litert.aot.ai_pack.export_lib``, from the files as they are -
nothing is recompiled, so the packed models are byte-identical to the
inputs - plus the pack's build.gradle.kts;
* the Google Tensor NPU runtime as an install-time feature module
(``litert_npu_runtime_libraries/google_tensor_runtime``, Maven artifact
``com.google.ai.edge.litert:litert-npu-runtime-google-tensor``) and its
``runtime_strings`` module, delivered to the same device groups as the
pack;
* the original model for the app's base assets (the CPU path), a Kotlin
loader (TensorModelLoader.kt), the model's input/output signature
(model_io.json), provenance (pack.json) and a step-by-step INTEGRATION.md.
Output (--output-dir, default <fallback model dir>/app_package/<pack name>):
INTEGRATION.md pack.json model_io.json
cpu_gpu/<model>_cpu_gpu.tflite (-> app assets litert/)
ai_packs/device_targeting_configuration.xml (-> app module)
ai_packs/<pack>/build.gradle.kts
ai_packs/<pack>/src/main/assets/model#group_Google_Tensor_G5/<model>.tflite
ai_packs/<pack>/src/main/assets/model#group_other/placeholder.txt
litert_npu_runtime_libraries/google_tensor_runtime/...
litert_npu_runtime_libraries/runtime_strings/...
kotlin/TensorModelLoader.kt
``model#group_other`` holds a placeholder instead of a second copy of the
original model: devices outside the Google Tensor groups use the base-asset
CPU model, so no device downloads the original twice (the exporter uses the
same placeholder technique for its MediaTek pack).
Update mode (--update-project <Gradle project root>) is for an app that
already ships Google Tensor builds in an AI pack and gets new ones. The script
reads the project without changing it: the pack, its device groups (matched
by SoC through the app's device-targeting XML), the runtime, the app's CPU
copy of the model and a generated TensorModelLoader. It runs the same input
checks and LiteRT export, then writes only the files to copy, under the
app's existing paths and names:
UPDATE.md update.json model_io.json
files/<path in the project> (one per Tensor build, plus the CPU copy)
(default --output-dir: <fallback model dir>/app_update/<pack name>). The
verdict is "drop-in" (only model files change), "structural" (UPDATE.md
lists the other edits: a new or dropped SoC, the runtime, changed model
inputs or outputs) or "up-to-date" (the project already has these files).
Check mode (--check-project <Gradle project root> --package <package dir>)
reads a project and checks it against a package this script wrote: every
requirement of its INTEGRATION.md (files, settings includes, the app's
Gradle setup, gradle.properties, permissions, plugin versions) comes back as
pass, fail or warn, with the exact fix and whether the fix is risky
(upgrades, a higher minSdk, replacing changed files). Run before applying a
package, it lists the plan; after, it confirms the project is complete.
Only the export step imports LiteRT, so --help and --dry-run work with any
python3. A real run needs a Python with ``ai-edge-litert`` (the compile venv
works; the Google Tensor SDK Beta is not needed for packaging).
Exit codes
----------
0 success (--check-project: every requirement passes)
1 --check-project only: at least one requirement fails (the report says what
to do)
2 bad input: missing file, duplicate SoC, invalid name, output exists, a
build that differs from its .compile.json sidecar, broken versions.json;
with --update-project also a project the script cannot update as is (no
or several Tensor AI packs, unknown CPU copy, a group with several SoCs)
3 wrong model kind: an uncompiled --compiled file, a compiled --fallback, or
a model compiled by another toolchain (Edge TPU custom op) for either
5 LiteRT not importable, or its AI-pack exporter API changed
7 post-export verification failed (nothing is left at --output-dir)
"""
from __future__ import annotations
import argparse
import datetime
import hashlib
import importlib.metadata
import json
import os
import pathlib
import re
import shlex
import shutil
import sys
from typing import Any
import xml.etree.ElementTree as ET
SKILL_DIR = pathlib.Path(__file__).resolve().parent.parent
VERSIONS_FILE = SKILL_DIR / "assets" / "versions.json"
TEMPLATES_DIR = SKILL_DIR / "assets" / "templates"
GENERATOR = "litert-google-tensor package_ai_pack.py"
SUPPORTED_TARGETS = ("Tensor_G5", "Tensor_G6")
PIXEL_FAMILY = {"Tensor_G5": "Pixel 10 family", "Tensor_G6": "Pixel 11 family"}
DELIVERY_TYPES = ("install-time", "fast-follow", "on-demand")
TFLITE_FILE_IDENTIFIER = b"TFL3" # flatbuffer identifier at byte offset 4..8
DISPATCH_OP_MARKER = b"DISPATCH_OP"
BUILD_STAMP_KEY = b"LiteRtStamp"
GOOGLE_MANUFACTURER = b"Google"
SOC_MODEL_RE = re.compile(rb"Tensor_G\d+")
# Custom op of models compiled by the Edge TPU compiler (and older Google
# Tensor tooling), same check as check_compiled.py.
LEGACY_TPU_OP_RE = re.compile(rb"edgetpu-custom-op[\w-]*")
PACK_NAME_RE = re.compile(r"[A-Za-z][A-Za-z0-9_]*")
MODEL_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*")
KOTLIN_PACKAGE_RE = re.compile(
r"[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*")
APP_MODULE_RE = re.compile(r"[A-Za-z0-9_.-]+(:[A-Za-z0-9_.-]+)*")
PLACEHOLDER_RE = re.compile(r"\{\{[A-Z0-9_]+\}\}")
DTC_NS = "http://schemas.android.com/apk/config"
DIST_NS = "http://schemas.android.com/apk/distribution"
OTHER_GROUP_DIR = "model#group_other"
PLACEHOLDER_FILE = "placeholder.txt"
# Optional quick test (--quick-test): quick_test/<SoC>/assets/ in the package
# goes to <app module>/tensor_quick_test/; the Gradle property picks the SoC.
QUICK_TEST_DIR = "quick_test"
APP_QUICK_TEST_DIR = "tensor_quick_test"
QUICK_TEST_PROPERTY = "tensorQuickTest"
PLACEHOLDER_TEXT = (
"Intentionally not a model. Devices outside the Google Tensor device\n"
"groups of this AI pack run the original model from the app's base\n"
"assets (litert/{model}_cpu_gpu.tflite), so they do not need a copy\n"
"here. Written by {generator}.\n"
)
# Template file (relative to assets/templates/) -> output file (relative to the
# output directory). ``{pack}`` is replaced by the pack name.
TEMPLATE_OUTPUTS = (
("ai_pack/build.gradle.kts", "ai_packs/{pack}/build.gradle.kts"),
(
"google_tensor_runtime/build.gradle.kts",
"litert_npu_runtime_libraries/google_tensor_runtime/build.gradle.kts",
),
(
"google_tensor_runtime/src/main/AndroidManifest.xml",
"litert_npu_runtime_libraries/google_tensor_runtime/src/main/"
+ "AndroidManifest.xml",
),
(
"runtime_strings/build.gradle.kts",
"litert_npu_runtime_libraries/runtime_strings/build.gradle.kts",
),
(
"runtime_strings/src/main/res/values/strings.xml",
"litert_npu_runtime_libraries/runtime_strings/src/main/res/values/"
+ "strings.xml",
),
("TensorModelLoader.kt", "kotlin/TensorModelLoader.kt"),
)
RUNTIME_MANIFEST = TEMPLATE_OUTPUTS[2][1]
# Notes shown next to files in INTEGRATION.md's tree.
TREE_NOTES = {
"INTEGRATION.md": "this guide",
"pack.json": "provenance: sources, SHA-256, versions",
"model_io.json": "input/output names, shapes and types",
"ai_packs/device_targeting_configuration.xml": "-> <app module>/",
"kotlin/TensorModelLoader.kt": "-> your sources",
}
class PackError(Exception):
"""A failure with the exit code to return and a message naming the fix."""
def __init__(self, code: int, message: str):
super().__init__(message)
self.code = code
# --------------------------------------------------------------------------
# versions.json
# --------------------------------------------------------------------------
def read_versions() -> tuple[dict[str, Any], str | None]:
"""Returns (versions, error); never raises, so --help/--dry-run work."""
try:
data = json.loads(VERSIONS_FILE.read_text(encoding="utf-8"))
except (OSError, ValueError) as e:
return {}, f"cannot read {VERSIONS_FILE}: {e}"
if not isinstance(data, dict):
return {}, f"{VERSIONS_FILE} is not a JSON object"
return data, None
def maven_release(versions: dict[str, Any], error: str | None) -> str:
"""The pinned Google Maven release of the LiteRT runtime artifacts."""
release = versions.get("maven_release")
if not isinstance(release, str) or not re.fullmatch(
r"\d[0-9A-Za-z.+_-]*", release
):
reason = error or "no valid 'maven_release' field"
raise PackError(
2,
f"{reason}. The generated Gradle files need the LiteRT Maven "
f"release from {VERSIONS_FILE}; restore that file from the skill.",
)
return release
def kotlin_min(versions: dict[str, Any], error: str | None) -> str:
"""Oldest Kotlin that can read the LiteRT Kotlin API at maven_release."""
value = versions.get("kotlin_min")
if not isinstance(value, str) or not re.fullmatch(r"\d+\.\d+(\.\d+)?",
value):
reason = error or "no valid 'kotlin_min' field"
raise PackError(
2,
f"{reason}. INTEGRATION.md needs the minimum Kotlin version from "
f"{VERSIONS_FILE}; restore that file from the skill.",
)
return value
# --------------------------------------------------------------------------
# Model inspection (standard library only, same markers as check_compiled.py)
# --------------------------------------------------------------------------
def scan_model(path: pathlib.Path) -> dict[str, Any]:
"""SHA-256 plus the compile markers of ``path``, read in 1 MiB chunks."""
digest = hashlib.sha256()
markers = {DISPATCH_OP_MARKER: False, BUILD_STAMP_KEY: False,
GOOGLE_MANUFACTURER: False}
socs: set[str] = set()
legacy: set[str] = set()
head = b""
carry = b""
size = 0
with open(path, "rb") as f:
chunk = f.read(1 << 20)
while chunk:
if not size:
head = chunk[:8]
digest.update(chunk)
size += len(chunk)
nxt = f.read(1 << 20)
window = carry + chunk
for marker, seen in markers.items():
if not seen and marker in window:
markers[marker] = True
for regex, found in ((SOC_MODEL_RE, socs), (LEGACY_TPU_OP_RE, legacy)):
for m in regex.finditer(window):
# A match touching the window end may continue in the next chunk;
# the carried tail lets the next window see it whole.
if nxt and m.end() == len(window):
continue
found.add(m.group().decode("ascii"))
carry = window[-32:]
chunk = nxt
is_tflite = len(head) >= 8 and head[4:8] == TFLITE_FILE_IDENTIFIER
compiled = (is_tflite and markers[DISPATCH_OP_MARKER]
and markers[BUILD_STAMP_KEY])
return {
"path": path,
"size_bytes": size,
"sha256": digest.hexdigest(),
"is_tflite": is_tflite,
"compiled": compiled,
"google_tensor": markers[GOOGLE_MANUFACTURER] and bool(socs),
"soc_models": sorted(socs),
# Compiled by another toolchain (Edge TPU custom op), not by LiteRT.
"legacy_ops": [] if compiled or not is_tflite else sorted(legacy),
}
def read_sidecar(model: pathlib.Path) -> dict[str, Any] | None:
"""The ``<model>.compile.json`` written by compile_model.py, if any."""
sidecar = model.with_name(model.name + ".compile.json")
if not sidecar.is_file():
return None
try:
data = json.loads(sidecar.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
return data if isinstance(data, dict) else None
def fmt_size(num_bytes: int) -> str:
"""'8,110,864 bytes (8.1 MB)'; MB = 10^6 bytes, as in the other scripts."""
text = f"{num_bytes:,} bytes"
if num_bytes >= 100_000:
text += f" ({num_bytes / 1e6:.1f} MB)"
return text
def group_of(soc: str) -> str:
"""'Tensor_G5' -> 'Google_Tensor_G5' (the exporter's device group name)."""
return f"Google_{soc}"
def soc_display(soc: str) -> str:
"""'Tensor_G5' -> 'Tensor G5' (Build.SOC_MODEL / ro.soc.model)."""
return soc.replace("_", " ")
def quick_test_file(soc: str, model: str) -> str:
"""Package path of a build for the optional quick test (--quick-test)."""
return f"{QUICK_TEST_DIR}/{soc}/assets/model/{model}.tflite"
# --------------------------------------------------------------------------
# Arguments and pre-checks
# --------------------------------------------------------------------------
def parse_args(argv=None) -> argparse.Namespace:
"""Parses the command line and applies the defaults of a new integration."""
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
"--compiled",
action="append",
metavar="TFLITE",
help=(
"A Google Tensor-compiled build (compile_model.py output); repeat "
"for each SoC, at most one per SoC. Its .compile.json sidecar, "
"when present, must describe this exact file. Required except "
"with --check-project."
),
)
parser.add_argument(
"--fallback",
metavar="TFLITE",
help=(
"The ORIGINAL uncompiled model the builds were compiled from: the "
"app's CPU path (base assets). Required except with "
"--check-project."
),
)
parser.add_argument(
"--pack-name",
help=(
"AI pack name and directory: a letter, then letters, digits or "
"'_' (default: the fallback file name made valid). With "
"--update-project: which of the app's packs to update, when "
"several ship Google Tensor builds."
),
)
parser.add_argument(
"--model-name",
help=(
"File name of the model inside the pack, without .tflite; the app "
"opens model/<name>.tflite (default: the pack name). With "
"--update-project: which model of the pack to update, when it "
"holds several."
),
)
parser.add_argument(
"--delivery",
choices=DELIVERY_TYPES,
help=(
"When Google Play puts the model on the phone (default "
"install-time: with the app, ready at first launch). "
"--update-project keeps the app's delivery mode."
),
)
parser.add_argument(
"--app-module",
help=(
"Gradle path of the app module, e.g. 'app' or 'apps:main' "
"(default: app); used in the generated Gradle files. With "
"--update-project: the module that lists the AI pack, when it "
"cannot be found."
),
)
parser.add_argument(
"--kotlin-package",
help=(
"package line of the generated TensorModelLoader.kt (default: "
"com.example.litert)."
),
)
parser.add_argument(
"--update-project",
metavar="DIR",
help=(
"Update mode, for an app that already ships Google Tensor builds "
"in an AI pack: the root of its Gradle project (the folder with "
"settings.gradle.kts). The project is only read; the files to "
"copy go to --output-dir with UPDATE.md."
),
)
parser.add_argument(
"--quick-test",
action="store_true",
help=(
"Also write quick_test/<SoC>/assets/: each Tensor build laid out "
"for a debug APK that carries it together with the NPU runtime, so "
"'./gradlew installDebug -PtensorQuickTest=<SoC>' runs the model on "
"a Pixel without bundletool (local testing only; INTEGRATION.md "
"has the steps)."
),
)
parser.add_argument(
"--check-project",
metavar="DIR",
help=(
"Check mode (read-only): is the Gradle project at DIR set up for "
"the package given with --package? Lists every requirement as "
"pass/fail/warn with the exact fix; exit 1 while something fails."
),
)
parser.add_argument(
"--package",
metavar="DIR",
help=(
"With --check-project: a package this script wrote (the folder "
"with INTEGRATION.md and pack.json)."
),
)
parser.add_argument(
"--cpu-asset",
metavar="PATH",
help=(
"With --update-project: the app's copy of the original model for "
"the CPU path, relative to the project root, when the script cannot "
"find it; 'none' if the app keeps no CPU copy."
),
)
parser.add_argument(
"--output-dir",
help=(
"Where to write the package (default: <fallback dir>/app_package/"
"<pack name>, or app_update/<pack name> with --update-project). "
"Must not exist unless --overwrite."
),
)
parser.add_argument(
"--overwrite",
action="store_true",
help=(
"Replace an existing --output-dir, but only one written by this "
"script (it has a pack.json from package_ai_pack.py)."
),
)
parser.add_argument(
"--allow-source-mismatch",
action="store_true",
help=(
"Package even if a build's sidecar says it was compiled from a "
"different file than --fallback (the CPU and TPU paths would then "
"run different models)."
),
)
parser.add_argument(
"--dry-run",
action="store_true",
help=(
"Run every input check and print the plan; import nothing and "
"write nothing."
),
)
parser.add_argument(
"--json", action="store_true", help="Print a JSON summary only."
)
args = parser.parse_args(argv)
# Flags the user passed (update mode rejects or checks them), then the
# defaults of a new integration.
args.explicit = {key for key in ("delivery", "app_module", "kotlin_package")
if getattr(args, key) is not None}
args.delivery = args.delivery or "install-time"
args.app_module = args.app_module or "app"
args.kotlin_package = args.kotlin_package or "com.example.litert"
return args
def default_pack_name(fallback: pathlib.Path) -> str:
name = re.sub(r"[^A-Za-z0-9_]", "_", fallback.stem)
if not name or not name[0].isalpha():
name = "model_" + name
return name
def legacy_message(flag: str, info: dict[str, Any]) -> str:
"""Error for a model compiled by another toolchain (Edge TPU custom op)."""
return (
f"{flag} {info['path'].name} was compiled by another toolchain: it "
f"holds an Edge TPU custom op ({', '.join(info['legacy_ops'])}), which "
"neither the Google Tensor runtime nor the CPU can run "
"(check_compiled.py exits 4 for such files). Use the ORIGINAL model it "
"was made from: as --fallback as is, and compiled with "
"compile_model.py for --compiled."
)
def check_names(args: argparse.Namespace, fallback: pathlib.Path) -> None:
"""Fills in, normalizes and validates the name flags of ``args``."""
args.pack_name = args.pack_name or default_pack_name(fallback)
if not PACK_NAME_RE.fullmatch(args.pack_name):
raise PackError(
2,
f"invalid --pack-name {args.pack_name!r}: AI pack names start with a "
"letter and contain only letters, digits and '_'.",
)
model = args.model_name or args.pack_name
model = model[: -len(".tflite")] if model.endswith(".tflite") else model
if not MODEL_NAME_RE.fullmatch(model):
raise PackError(
2,
f"invalid --model-name {model!r}: use letters, digits, '_', '.' or "
"'-', starting with a letter or digit.",
)
args.model_name = model
if not KOTLIN_PACKAGE_RE.fullmatch(args.kotlin_package):
raise PackError(
2, f"invalid --kotlin-package {args.kotlin_package!r} (e.g. "
"com.example.myapp.ml)."
)
module = args.app_module.lstrip(":")
if not APP_MODULE_RE.fullmatch(module):
raise PackError(
2, f"invalid --app-module {args.app_module!r} (e.g. app or apps:main)."
)
args.app_module = module
def check_inputs(args: argparse.Namespace) -> tuple[dict[str, dict[str, Any]],
dict[str, Any], list[str]]:
"""Validates the models; returns (builds by SoC, fallback info, notes)."""
notes: list[str] = []
fallback_path = pathlib.Path(args.fallback).expanduser().resolve()
if not fallback_path.is_file():
raise PackError(2, f"--fallback not found: {fallback_path}")
fallback = scan_model(fallback_path)
if not fallback["is_tflite"]:
raise PackError(2, f"--fallback is not a .tflite flatbuffer: "
f"{fallback_path}")
if fallback["legacy_ops"]:
raise PackError(3, legacy_message("--fallback", fallback))
if fallback["compiled"]:
raise PackError(
3,
f"--fallback {fallback_path.name} is a compiled build (SoC: "
f"{', '.join(fallback['soc_models']) or 'unknown'}). Pass the "
"ORIGINAL uncompiled model: compiled builds cannot run on the CPU.",
)
builds: dict[str, dict[str, Any]] = {}
for raw in args.compiled:
path = pathlib.Path(raw).expanduser().resolve()
if not path.is_file():
raise PackError(2, f"--compiled not found: {path}")
info = scan_model(path)
if not info["is_tflite"]:
raise PackError(2, f"--compiled is not a .tflite flatbuffer: {path}")
if info["legacy_ops"]:
raise PackError(3, legacy_message("--compiled", info))
if not (info["compiled"] and info["google_tensor"]):
raise PackError(
3,
f"--compiled {path.name} is not compiled for Google Tensor. "
"Compile it with compile_model.py first (check_compiled.py tells "
"you which files are compiled).",
)
if len(info["soc_models"]) != 1:
raise PackError(
2,
f"--compiled {path.name} names several SoCs "
f"({', '.join(info['soc_models'])}); cannot tell which device "
"group it belongs to.",
)
soc = info["soc_models"][0]
if soc not in SUPPORTED_TARGETS:
raise PackError(
2,
f"--compiled {path.name} is compiled for {soc}; this skill "
f"packages {' and '.join(SUPPORTED_TARGETS)} builds only.",
)
if soc in builds:
raise PackError(
2,
f"two --compiled builds for {soc}: {builds[soc]['path'].name} and "
f"{path.name}. Pass one build per SoC.",
)
sidecar = read_sidecar(path)
info["sidecar"] = sidecar
if sidecar is None:
notes.append(
f"{path.name}: no .compile.json sidecar (not compiled by "
"compile_model.py, or moved without it); flags and op counts "
"unknown."
)
else:
if sidecar.get("output_sha256") not in (None, info["sha256"]):
raise PackError(
2,
f"{path.name} differs from the build its .compile.json describes "
"(SHA-256 mismatch): the file changed after it was compiled. Use "
"the build that was compiled and benchmarked, or recompile.",
)
if sidecar.get("target") not in (None, soc):
raise PackError(
2,
f"{path.name}: the sidecar says {sidecar.get('target')} but the "
f"file is stamped {soc}; the sidecar belongs to another build.",
)
source = sidecar.get("input_sha256")
if source and source != fallback["sha256"]:
if not args.allow_source_mismatch:
raise PackError(
2,
f"{path.name} was compiled from a different file than "
f"--fallback {fallback_path.name} (input SHA-256 in its "
"sidecar). Pass the original it was compiled from, so the "
"CPU and TPU paths run the same model, or add "
"--allow-source-mismatch.",
)
notes.append(
f"{path.name}: compiled from a different file than --fallback "
"(--allow-source-mismatch)."
)
fully_compiled = sidecar.get("fully_compiled")
if isinstance(fully_compiled, bool) and not fully_compiled:
notes.append(
f"{path.name}: only {sidecar.get('ops_offloaded')} / "
f"{sidecar.get('ops_total')} ops run on the TPU; the rest run on "
"the CPU in the app."
)
builds[soc] = info
return dict(sorted(builds.items())), fallback, notes
def resolve_output_dir(args: argparse.Namespace,
fallback: dict[str, Any]) -> pathlib.Path:
"""Output directory of the package, checked against --overwrite."""
if args.output_dir:
out = pathlib.Path(args.output_dir).expanduser().resolve()
else:
out = fallback["path"].parent / "app_package" / args.pack_name
if out.exists():
if not args.overwrite:
raise PackError(
2,
f"output already exists: {out}. Choose another --output-dir, or "
"pass --overwrite to replace a package written by this script.",
)
if not _written_by_us(out):
raise PackError(
2,
f"refusing to replace {out}: it is not empty and has no pack.json "
"from package_ai_pack.py. Choose another --output-dir.",
)
return out
def _written_by_us(path: pathlib.Path) -> bool:
"""An empty directory, or a package or update plan from this script."""
if path.is_dir() and not any(path.iterdir()):
return True
for summary in ("pack.json", "update.json"):
try:
data = json.loads((path / summary).read_text(encoding="utf-8"))
except (OSError, ValueError):
continue
if isinstance(data, dict) and data.get("generator") == GENERATOR:
return True
return False
# --------------------------------------------------------------------------
# Export with LiteRT
# --------------------------------------------------------------------------
def installed_litert() -> str | None:
for dist in ("ai-edge-litert", "ai-edge-litert-nightly"):
try:
return f"{dist} {importlib.metadata.version(dist)}"
except importlib.metadata.PackageNotFoundError:
continue
return None
def export_with_litert(builds: dict[str, dict[str, Any]],
fallback: dict[str, Any],
ai_packs_dir: pathlib.Path, pack: str, model: str,
pip_release: str | None) -> None:
"""Writes the AI pack with ai_edge_litert.aot.ai_pack.export_lib."""
pin = pip_release or "<pip_release in versions.json>"
os.environ.setdefault("GOOGLE_TENSOR_BACKEND_ENABLED", "1")
try:
# pylint: disable=g-import-not-at-top
from ai_edge_litert.aot.ai_pack import export_lib
try: # The module was renamed between LiteRT releases.
from ai_edge_litert.aot.core import aot_types
except ImportError:
from ai_edge_litert.aot.core import types as aot_types
from ai_edge_litert.aot.vendors import fallback_backend
from ai_edge_litert.aot.vendors.google_tensor import google_tensor_backend
# pylint: enable=g-import-not-at-top
except ImportError as e:
raise PackError(
5,
f"LiteRT's AI-pack exporter is not importable with {sys.executable} "
f"({e}). Run this script with the Python of the venv that has "
"ai-edge-litert (the compile venv works), or create one: "
f"python3 -m venv ~/.venvs/litert-pack && ~/.venvs/litert-pack/bin/"
f"pip install ai-edge-litert=={pin}. The Google Tensor SDK Beta is "
"not needed for packaging.",
) from e
try:
tensor_backend = google_tensor_backend.GoogleTensorBackend
models_with_backend = []
for soc, info in builds.items():
backend = tensor_backend.create(
{"backend_id": tensor_backend.id(), "soc_model": soc}
)
models_with_backend.append(
(backend, aot_types.Model.create_from_path(info["path"]))
)
other = fallback_backend.FallbackBackend
models_with_backend.append((
other.create({"backend_id": other.id()}),
aot_types.Model.create_from_path(fallback["path"]),
))
result = aot_types.CompilationResult(
models_with_backend=models_with_backend
)
export_lib.export(result, ai_packs_dir, pack, model)
except (AssertionError, AttributeError, KeyError, TypeError,
ValueError) as e:
raise PackError(
5,
f"LiteRT's AI-pack exporter failed ({type(e).__name__}: {e}) with "
f"{installed_litert() or 'an unknown ai-edge-litert'}; this script "
f"is verified with ai-edge-litert {pin}. Use that version "
"(compile_model.py --print-install); if it already is, export_lib "
"changed: see references/contributing.md.",
) from e
# --------------------------------------------------------------------------
# Generated files
# --------------------------------------------------------------------------
def render(template: str, values: dict[str, str]) -> str:
"""Fills the {{KEY}} placeholders of a skill template with ``values``."""
path = TEMPLATES_DIR / template
try:
text = path.read_text(encoding="utf-8")
except OSError as e:
raise PackError(
2,
f"skill template missing: {path} ({e}). Install the whole skill "
"folder, including assets/templates/.",
) from e
for key, value in values.items():
text = text.replace("{{" + key + "}}", value)
left = sorted(set(PLACEHOLDER_RE.findall(text)))
if left:
raise PackError(
7,
f"template {template} has unfilled placeholders {left}: "
"assets/templates/ and package_ai_pack.py are out of sync.",
)
return text
def template_values(args: argparse.Namespace, builds: dict[str, dict[str, Any]],
release: str, min_kotlin: str) -> dict[str, str]:
"""Values for the placeholders of the templates in assets/templates/."""
socs = list(builds)
groups = [group_of(s) for s in socs]
indent = " " * 24
module_dir = args.app_module.replace(":", "/")
if args.delivery == "install-time":
permissions = "nothing to add for `install-time` delivery."
else:
permissions = (
f"`{args.delivery}` packs are downloaded by the Play AI Delivery "
"library, which needs these permissions in\n"
f" `{module_dir}/src/main/AndroidManifest.xml`:\n\n"
" ```xml\n"
' <uses-permission android:name="android.permission.'
'FOREGROUND_SERVICE" />\n'
' <uses-permission android:name="android.permission.'
'FOREGROUND_SERVICE_DATA_SYNC" />\n'
" ```\n\n"
" The loader uses the CPU model when a download waits for Wi-Fi "
"or for the\n"
" user's confirmation (downloads over 200 MB on mobile data); "
"call\n"
" `AiPackManager.showConfirmationDialog()` yourself for large "
"models."
)
return {
"PACK_NAME": args.pack_name,
"MODEL_NAME": args.model_name,
"DELIVERY": args.delivery,
"APP_MODULE": args.app_module,
"APP_MODULE_DIR": module_dir,
"APP_MODULE_LAST": args.app_module.split(":")[-1],
"KOTLIN_PACKAGE": args.kotlin_package,
"KOTLIN_MIN": min_kotlin,
"LITERT_MAVEN_RELEASE": release,
"DEVICE_GROUP_ELEMENTS": "\n".join(
f'{indent}<dist:device-group dist:name="{g}"/>' for g in groups
),
"SOC_MODELS_KOTLIN": ", ".join(f'"{soc_display(s)}"' for s in socs),
"SOC_LIST_TEXT": ", ".join(
f"{soc_display(s)}, {PIXEL_FAMILY.get(s, 'Pixel')}" for s in socs
),
"GROUP_LIST": ", ".join(
f"`{group_of(s)}` ({soc_display(s)}, "
f"{PIXEL_FAMILY.get(s, 'Pixel')})" for s in socs
),
"FIRST_GROUP": groups[0],
"PERMISSIONS_STEP": permissions,
# Filled with assets/templates/INTEGRATION_quick_test.md for --quick-test.
"QUICK_TEST_SECTION": "",
"FIRST_SOC": socs[0],
"QUICK_TEST_SOCS": " and ".join(f"`{s}`" for s in socs),
}
def read_model_io(model: pathlib.Path) -> dict[str, Any]:
"""Signatures (input/output names, shapes, types) of an uncompiled model.
Args:
model: The uncompiled .tflite model.
Returns:
{"source", "signatures"}, plus "error" if LiteRT could not read it.
"""
data: dict[str, Any] = {"source": model.name, "signatures": []}
try:
# pylint: disable-next=g-import-not-at-top
from ai_edge_litert.interpreter import Interpreter
interpreter = Interpreter(model_path=str(model))
def describe(details) -> dict[str, Any]:
return {
"shape": [int(x) for x in details["shape"]],
"dtype": getattr(details["dtype"], "__name__",
str(details["dtype"])),
}
signatures = interpreter.get_signature_list() or {}
for key in signatures:
runner = interpreter.get_signature_runner(key)
data["signatures"].append({
"key": key,
"inputs": [dict(name=n, **describe(d))
for n, d in runner.get_input_details().items()],
"outputs": [dict(name=n, **describe(d))
for n, d in runner.get_output_details().items()],
})
if not signatures:
data["signatures"].append({
"key": "",
"inputs": [dict(name=d["name"], **describe(d))
for d in interpreter.get_input_details()],
"outputs": [dict(name=d["name"], **describe(d))
for d in interpreter.get_output_details()],
})
except Exception as e: # pylint: disable=broad-exception-caught
data["error"] = f"{type(e).__name__}: {e}"
return data
def dump_model_io(data: dict[str, Any], path: pathlib.Path) -> None:
"""Writes read_model_io() output as model_io.json."""
text = json.dumps(data, indent=2)
# Keep shapes on one line: "shape": [1, 3, 224, 224].
text = re.sub(
r"\[\s*(-?\d+(?:\s*,\s*-?\d+)*)\s*\]",
lambda m: "[" + ", ".join(x.strip() for x in m.group(1).split(",")) + "]",
text,
)
path.write_text(text + "\n", encoding="utf-8")
def write_model_io(fallback: pathlib.Path, out: pathlib.Path) -> str | None:
"""Writes model_io.json from the original model; returns an error or None."""
data = read_model_io(fallback)
dump_model_io(data, out / "model_io.json")
return data.get("error")
def tree_text(root: pathlib.Path) -> str:
"""The file tree of ``root`` for INTEGRATION.md, with notes on some files."""
files = sorted(
str(p.relative_to(root)) for p in root.rglob("*") if p.is_file()
)
files = ["INTEGRATION.md"] + [f for f in files if f != "INTEGRATION.md"]
def note(f: str) -> str | None:
if f.startswith("cpu_gpu/"):
return "-> <app module>/src/main/assets/litert/"
if f.startswith(QUICK_TEST_DIR + "/"):
return f"-> <app module>/{APP_QUICK_TEST_DIR}/ (optional quick test)"
return TREE_NOTES.get(f)
width = max(len(f) for f in files if note(f)) + 2
return "\n".join(f"{f:<{width}}{note(f)}" if note(f) else f for f in files)
# --------------------------------------------------------------------------
# Verification
# --------------------------------------------------------------------------
def _verify_fail(message: str):
raise PackError(7, f"post-export verification failed: {message}")
def check_exported_builds(stage: pathlib.Path, assets: pathlib.Path,
model: str,
builds: dict[str, dict[str, Any]]) -> list[str]:
"""Exporter output: one folder per SoC plus other, byte-identical builds."""
passed: list[str] = []
expected = {f"model#group_{group_of(s)}" for s in builds} | {OTHER_GROUP_DIR}
found = {p.name for p in assets.iterdir()} if assets.is_dir() else set()
if found != expected:
_verify_fail(
f"AI pack folders are {sorted(found)}, expected {sorted(expected)}.")
passed.append("AI pack folders: " + ", ".join(sorted(expected)))
for soc, info in builds.items():
packed = assets / f"model#group_{group_of(soc)}" / f"{model}.tflite"
if not packed.is_file():
_verify_fail(f"missing {packed.relative_to(stage)}.")
got = scan_model(packed)
if got["sha256"] != info["sha256"]:
_verify_fail(f"{packed.relative_to(stage)} is not byte-identical to "
f"{info['path']}.")
if not got["compiled"] or got["soc_models"] != [soc]:
_verify_fail(f"{packed.relative_to(stage)} is not stamped {soc}.")
passed.append(f"{group_of(soc)}: byte-identical to {info['path'].name}, "
f"stamped {soc}")
return passed
def check_exported_dtc(dtc: pathlib.Path,
builds: dict[str, dict[str, Any]]) -> str:
"""The exporter's XML defines exactly one Google SoC group per build."""
groups = {group_of(s): soc_display(s) for s in builds}
try:
root = ET.parse(dtc).getroot()
except (OSError, ET.ParseError) as e:
_verify_fail(f"cannot parse {dtc.name}: {e}")
found_groups = {}
for group in root.findall(f"{{{DTC_NS}}}device-group"):
socs = [(s.get("manufacturer"), s.get("model"))
for s in group.iter(f"{{{DTC_NS}}}system-on-chip")]
found_groups[group.get("name")] = socs
want = {g: [("Google", m)] for g, m in groups.items()}
if found_groups != want:
_verify_fail(f"{dtc.name} defines {found_groups}, expected {want}.")
return "device_targeting_configuration.xml: " + ", ".join(
f'{g} = Google "{m}"' for g, m in groups.items())
def verify_package(stage: pathlib.Path, args: argparse.Namespace,
builds: dict[str, dict[str, Any]],
fallback: dict[str, Any]) -> list[str]:
"""Checks the staged package; returns the list of passed checks."""
fail = _verify_fail
assets = stage / "ai_packs" / args.pack_name / "src" / "main" / "assets"
passed = check_exported_builds(stage, assets, args.model_name, builds)
other = sorted(p.name for p in (assets / OTHER_GROUP_DIR).iterdir())
if other != [PLACEHOLDER_FILE]:
fail(f"{OTHER_GROUP_DIR} holds {other}, expected only {PLACEHOLDER_FILE}.")
passed.append(f"{OTHER_GROUP_DIR}: placeholder only")
groups = {group_of(s): soc_display(s) for s in builds}
passed.append(check_exported_dtc(
stage / "ai_packs" / "device_targeting_configuration.xml", builds))
manifest = stage / RUNTIME_MANIFEST
try:
mroot = ET.parse(manifest).getroot()
except (OSError, ET.ParseError) as e:
fail(f"cannot parse the runtime module manifest: {e}")
module_groups = sorted(
g.get(f"{{{DIST_NS}}}name")
for g in mroot.iter(f"{{{DIST_NS}}}device-group")
)
if module_groups != sorted(groups):
fail(f"google_tensor_runtime is delivered to {module_groups}, but the "
f"AI pack defines {sorted(groups)}.")
passed.append("google_tensor_runtime delivered to the same groups")
cpu = stage / "cpu_gpu" / f"{args.model_name}_cpu_gpu.tflite"
if not cpu.is_file() or scan_model(cpu)["sha256"] != fallback["sha256"]:
fail(f"{cpu.relative_to(stage)} is not byte-identical to "
f"{fallback['path']}.")
passed.append(f"CPU model: byte-identical to {fallback['path'].name}")
quick = stage / QUICK_TEST_DIR
found = sorted(p.relative_to(stage).as_posix() for p in quick.rglob("*")
if p.is_file()) if quick.is_dir() else []
want = sorted(quick_test_file(s, args.model_name)
for s in builds) if args.quick_test else []
if found != want:
fail(f"quick test files are {found}, expected {want}.")
for soc, info in builds.items() if args.quick_test else ():
got = scan_model(stage / quick_test_file(soc, args.model_name))
if got["sha256"] != info["sha256"] or got["soc_models"] != [soc]:
fail(f"{quick_test_file(soc, args.model_name)} is not byte-identical "
f"to {info['path']}.")
if args.quick_test:
passed.append("quick test: one byte-identical build per SoC")
for path in stage.rglob("*"):
if path.is_file() and path.suffix in (".kts", ".xml", ".kt", ".md"):
left = PLACEHOLDER_RE.findall(path.read_text(encoding="utf-8"))
if left:
fail(f"{path.relative_to(stage)} has unfilled placeholders {left}.")
passed.append("generated files: no unfilled placeholders")
return passed
# --------------------------------------------------------------------------
# Update mode (--update-project): new builds for a model the app ships
# --------------------------------------------------------------------------
UPDATE_SUMMARY = "update.json"
EXPORT_PACK = "tensor_update" # names inside the staging export only
EXPORT_MODEL = "model"
SETTINGS_FILES = ("settings.gradle.kts", "settings.gradle")
BUILD_FILES = ("build.gradle.kts", "build.gradle")
SKIP_DIRS = frozenset({"build", "out", "node_modules"})
MAX_WALK_DEPTH = 16
MAX_SOURCE_BYTES = 1 << 20
TENSOR_SOC_RE = re.compile(r"Tensor G\d+")
GROUP_DIR_RE = re.compile(r"(?P<prefix>.+)#group_(?P<group>[A-Za-z0-9_]+)")
DISPATCH_LIB_NAME = "libLiteRtDispatch_GoogleTensor.so"
LITERT_MAVEN_GROUP = "com.google.ai.edge.litert"
RUNTIME_ARTIFACT = "litert-npu-runtime-google-tensor"
CORE_ARTIFACT = "litert"
RUNTIME_AAR_URL = (
"https://dl.google.com/dl/android/maven2/com/google/ai/edge/litert/"
"litert-npu-runtime-google-tensor/{release}/"
"litert-npu-runtime-google-tensor-{release}.aar"
)
BENCHMARK_SCRIPT = SKILL_DIR / "scripts" / "benchmark_on_device.py"
# The element LiteRT's exporter writes for a group; a real run takes it from
# the exporter's own output instead.
DTC_GROUP_SNIPPET = (
'<config:device-group name="{group}">\n'
" <config:device-selector>\n"
' <config:system-on-chip manufacturer="Google" model="{model}"/>\n'
" </config:device-selector>\n"
"</config:device-group>"
)
VERDICTS = {
"drop-in": "drop-in: only the model files change",
"structural": "structural: the model files plus other changes",
"up-to-date": "up to date: the project already has these exact files",
}
DELIVERY_UPDATE = {
"install-time": "Phones get the new model with the app update.",
"fast-follow": (
"The app update invalidates the pack downloaded before; Google Play "
"downloads the new one automatically right after the update."
),
"on-demand": (
"The app update invalidates the pack downloaded before; the new one "
"is downloaded the next time the app requests it."
),
}
_COMMENT_RE = re.compile(
r"(\"(?:\\.|[^\"\\\n])*\"|'(?:\\.|[^'\\\n])*')|//[^\n]*|/\*.*?\*/", re.S
)
_QUOTED_RE = re.compile(r"[\"'](:?[\w.\-:]+)[\"']")
_INCLUDE_RE = re.compile(r"\binclude\s*\(([^)]*)\)|\binclude[ \t]+([^\n]+)")
_PROJECT_DIR_RE = re.compile(
r"project\(\s*[\"'](:?[\w.\-:]+)[\"']\s*\)\s*\.projectDir\s*=\s*"
r"(?:file|File|new\s+File)\s*\(\s*(?:(?:settingsDir|rootDir)\s*,\s*)?"
r"[\"']([^\"']+)[\"']"
)
_PACK_BLOCK_RE = re.compile(r"\b(aiPack|assetPack)\s*\{")
_SETTER = r"\s*(?:=|\.set\s*\(|[ \t]+)\s*"
_PACK_NAME_RE = re.compile(r"\bpackName\b" + _SETTER + r"[\"']([^\"']+)[\"']")
_DELIVERY_RE = re.compile(
r"\bdeliveryType\b" + _SETTER + r"[\"']([\w\-]+)[\"']")
_DEFAULT_GROUP_RE = re.compile(
r"\bdefaultGroup\b" + _SETTER + r"[\"']([A-Za-z0-9_]+)[\"']")
_DTC_RE = re.compile(
r"\bdeviceTargetingConfig\b\s*(?:=|\.set\s*\()?\s*"
r"(?P<fn>rootProject\.file|project\.file|layout\.projectDirectory\.file|"
r"file)\s*\(\s*[\"'](?P<path>[^\"']+)[\"']"
)
_VERSION_CODE_RE = re.compile(r"\bversionCode\b\s*(?:=\s*|[ \t]+)(\d+)")
_APP_ID_RE = re.compile(
r"\bapplicationId\b\s*(?:=\s*|[ \t]+)[\"']([\w.]+)[\"']")
_LOADER_CONSTS = {
"pack": re.compile(r"\bAI_PACK_NAME\s*=\s*\"([^\"]*)\""),
"model_path": re.compile(r"\bPACK_MODEL_PATH\s*=\s*\"([^\"]*)\""),
"cpu_asset": re.compile(r"\bCPU_MODEL_ASSET\s*=\s*\"([^\"]*)\""),
"delivery": re.compile(r"\bDELIVERY\s*=\s*\"([^\"]*)\""),
}
_LOADER_SOCS_RE = re.compile(
r"\bPACKAGED_SOC_MODELS\b[^=\n]*=\s*setOf\(([^)]*)\)")
def _read_text(path: pathlib.Path) -> str:
try:
return path.read_text(encoding="utf-8", errors="replace")
except OSError:
return ""
def _strip_comments(text: str) -> str:
"""Gradle (Kotlin or Groovy) source without its // and /* */ comments."""
return _COMMENT_RE.sub(lambda m: m.group(1) or "", text)
def _rel(path: pathlib.Path, root: pathlib.Path) -> str:
try:
return path.relative_to(root).as_posix()
except ValueError:
return str(path)
def _walk(top: pathlib.Path, max_depth: int = MAX_WALK_DEPTH):
"""os.walk below ``top``, skipping build outputs and hidden folders."""
base = len(top.parts)
for dirpath, dirnames, filenames in os.walk(top):
here = pathlib.Path(dirpath)
if len(here.parts) - base >= max_depth:
dirnames[:] = []
else:
dirnames[:] = sorted(d for d in dirnames
if d not in SKIP_DIRS and not d.startswith("."))
yield here, dirnames, sorted(filenames)
def _sha256(path: pathlib.Path) -> str:
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def project_root(raw: str) -> tuple[pathlib.Path, pathlib.Path]:
"""(root, settings file) of the Gradle project given to --update-project."""
root = pathlib.Path(raw).expanduser().resolve()
if not root.is_dir():
raise PackError(2, f"--update-project {root} is not a directory.")
for name in SETTINGS_FILES:
if (root / name).is_file():
return root, root / name
hint = ""
for parent in list(root.parents)[:3]:
if any((parent / name).is_file() for name in SETTINGS_FILES):
hint = f" {parent} has one: is that the project root?"
break
raise PackError(
2,
f"no settings.gradle.kts or settings.gradle in {root}. Pass the root "
f"folder of the app's Gradle project to --update-project.{hint}",
)
def parse_settings(root: pathlib.Path,
settings: pathlib.Path) -> dict[str, pathlib.Path]:
"""{Gradle path: module directory} from the include lines of settings."""
text = _strip_comments(_read_text(settings))
modules: dict[str, pathlib.Path] = {}
for m in _INCLUDE_RE.finditer(text):
for path in _QUOTED_RE.findall(m.group(1) or m.group(2) or ""):
gradle_path = ":" + path.lstrip(":")
modules[gradle_path] = root.joinpath(*gradle_path[1:].split(":"))
for m in _PROJECT_DIR_RE.finditer(text):
modules[":" + m.group(1).lstrip(":")] = (root / m.group(2)).resolve()
return modules
def inspect_project(raw_root: str) -> dict[str, Any]:
"""Reads the app's Gradle project; never writes to it."""
root, settings = project_root(raw_root)
gradle_paths = parse_settings(root, settings)
by_dir = {d: p for p, d in gradle_paths.items()}
modules, so_files, sources = [], [], []
for here, _, files in _walk(root):
build = next((name for name in BUILD_FILES if name in files), None)
if build:
modules.append({
"dir": here,
"rel": _rel(here, root),
"build_file": _rel(here / build, root),
"text": _strip_comments(_read_text(here / build)),
"gradle_path": ":" if here == root else by_dir.get(here),
})
if DISPATCH_LIB_NAME in files:
so_files.append(here / DISPATCH_LIB_NAME)
if "src" in here.relative_to(root).parts:
for name in files:
path = here / name
if name.endswith((".kt", ".java")) and _small(path):
text = _read_text(path)
if "SOC_MODEL" in text:
sources.append((path, text))
catalog, catalog_error = read_catalog(root)
return {
"root": root,
"settings_rel": _rel(settings, root),
"settings_text": _strip_comments(_read_text(settings)),
"gradle_paths": set(gradle_paths),
"modules": modules,
"so_files": so_files,
"sources": sources,
"catalog": catalog,
"catalog_error": catalog_error,
"properties": _read_text(root / "gradle.properties"),
}
def _small(path: pathlib.Path) -> bool:
try:
return path.stat().st_size <= MAX_SOURCE_BYTES
except OSError:
return False
def find_packs(project: dict[str, Any]) -> list[dict[str, Any]]:
"""AI packs (or asset packs) with device-group folders in their assets."""
packs = []
for module in project["modules"]:
block = _PACK_BLOCK_RE.search(module["text"])
assets = module["dir"] / "src" / "main" / "assets"
if not block or not assets.is_dir():
continue
group_dirs = []
for here, dirnames, _ in _walk(assets, max_depth=4):
for name in list(dirnames):
m = GROUP_DIR_RE.fullmatch(name)
if m:
dirnames.remove(name)
group_dirs.append({
"dir": here / name,
"prefix": _rel(here / m.group("prefix"), assets),
"group": m.group("group"),
})
if not group_dirs:
continue
name = _PACK_NAME_RE.search(module["text"])
delivery = _DELIVERY_RE.search(module["text"])
packs.append({
"module": module,
"kind": block.group(1),
"name": name.group(1) if name else module["dir"].name,
"delivery": (delivery.group(1) if delivery
and delivery.group(1) in DELIVERY_TYPES else None),
"assets": assets,
"group_dirs": group_dirs,
})
return packs
def find_dtcs(project: dict[str, Any]) -> list[dict[str, Any]]:
"""Device-targeting configs named by deviceTargetingConfig = file(...)."""
root = project["root"]
found = []
for module in project["modules"]:
m = _DTC_RE.search(module["text"])
if not m:
continue
path = pathlib.Path(m.group("path")).expanduser()
if not path.is_absolute():
base = root if m.group("fn") == "rootProject.file" else module["dir"]
path = base / path
found.append({
"module": module,
"path": path,
"rel": _rel(path, root),
"groups": parse_dtc(path) if path.is_file() else None,
})
return found
def parse_dtc(path: pathlib.Path) -> dict[str, dict[str, Any]]:
"""{group name: {"socs": [(manufacturer, model), ...]}} of an XML config."""
try:
tree = ET.parse(path).getroot()
except (OSError, ET.ParseError) as e:
raise PackError(
2,
f"cannot read the app's device-targeting config {path} ({e}). "
"bundletool cannot use it either: fix the XML, then re-run.",
) from e
groups = {}
for group in tree.iter(f"{{{DTC_NS}}}device-group"):
groups[group.get("name")] = {"socs": [
(s.get("manufacturer"), s.get("model"))
for s in group.iter(f"{{{DTC_NS}}}system-on-chip")
]}
return groups
def group_soc(info: dict[str, Any] | None) -> str | None:
"""'Tensor_G5' for a group that selects exactly one Google Tensor SoC.
'several' when it selects a Google Tensor SoC among others (a compiled
build runs on one SoC only); None when it selects no Google Tensor SoC.
Args:
info: A device group from parse_dtc(), or None.
Returns:
The SoC (e.g. 'Tensor_G5'), 'several' or None, as described above.
"""
if not info:
return None
tensor = [model for maker, model in info["socs"]
if maker == "Google" and model and TENSOR_SOC_RE.fullmatch(model)]
if not tensor:
return None
if len(info["socs"]) > 1:
return "several"
return tensor[0].replace(" ", "_")
def _stamped_socs(group_dir: pathlib.Path) -> list[str]:
socs = []
for path in sorted(group_dir.glob("*.tflite")):
info = scan_model(path)
if info["compiled"] and info["google_tensor"]:
socs += info["soc_models"]
return socs
def app_module_for(pack: dict[str, Any], project: dict[str, Any],
args: argparse.Namespace) -> dict[str, Any] | None:
"""The module whose assetPacks lists ``pack`` (or the --app-module)."""
modules = project["modules"]
if "app_module" in args.explicit:
want = args.app_module.strip(":")
for module in modules:
if ((module["gradle_path"] or "").strip(":") == want
or module["rel"] == want.replace(":", "/")):
return module
raise PackError(
2,
f"--app-module {args.app_module}: no such module in "
f"{project['root']}.",
)
pack_module = pack["module"]
hits = []
for module in modules:
if module is pack_module or "assetPacks" not in module["text"]:
continue
paths = re.findall(r"[\"'](:[\w.\-:]+)[\"']", module["text"])
if pack_module["gradle_path"] in paths or any(
p.rsplit(":", 1)[-1] == pack_module["dir"].name for p in paths):
hits.append(module)
return hits[0] if len(hits) == 1 else None
def read_catalog(root: pathlib.Path) -> tuple[dict[str, Any], str | None]:
"""Libraries, plugins and versions of gradle/libs.versions.toml."""
catalog: dict[str, Any] = {"libraries": {}, "plugins": {}, "versions": {}}
path = root / "gradle" / "libs.versions.toml"
if not path.is_file():
return catalog, None
text = _read_text(path)
try:
import tomllib # pylint: disable=g-import-not-at-top
except ImportError: # Python < 3.11
data = _mini_toml(text)
else:
try:
data = tomllib.loads(text)
except tomllib.TOMLDecodeError as e:
return catalog, (f"cannot parse {path} ({e}); versions declared there "
"are unknown")
versions = data.get("versions") or {}
catalog["versions"] = versions
for alias, spec in (data.get("libraries") or {}).items():
group = name = version = None
if isinstance(spec, str):
parts = spec.split(":")
group, name = (parts + [None, None])[:2]
version = parts[2] if len(parts) > 2 else None
elif isinstance(spec, dict):
if isinstance(spec.get("module"), str):
group, _, name = spec["module"].partition(":")
else:
group, name = spec.get("group"), spec.get("name")
version = _catalog_version(spec.get("version", spec), versions)
catalog["libraries"][alias] = {"group": group, "name": name,
"version": version}
for alias, spec in (data.get("plugins") or {}).items():
plugin_id = version = None
if isinstance(spec, str):
plugin_id, _, version = spec.partition(":")
elif isinstance(spec, dict):
plugin_id = spec.get("id")
version = _catalog_version(spec.get("version", spec), versions)
catalog["plugins"][alias] = {"id": plugin_id, "version": version or None}
return catalog, None
def _catalog_version(value, versions: dict[str, Any]) -> str | None:
if isinstance(value, str):
return value
if isinstance(value, dict):
if isinstance(value.get("ref"), str):
return _catalog_version(versions.get(value["ref"]), {})
for key in ("strictly", "require", "prefer"):
if isinstance(value.get(key), str):
return value[key]
return None
def _mini_toml(text: str) -> dict[str, Any]:
"""The [versions] and [libraries] tables, for Pythons without tomllib."""
data: dict[str, Any] = {}
table = None
for raw in text.splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
header = re.fullmatch(r"\[\s*([\w.\-]+)\s*\]", line)
if header:
table = data.setdefault(header.group(1), {})
continue
entry = re.fullmatch(r"([\w.\-]+|\"[^\"]+\")\s*=\s*(.+)", line)
if table is None or not entry:
continue
key, value = entry.group(1).strip('"'), entry.group(2).strip()
if value.startswith("{"):
item: dict[str, Any] = {}
for k, v in re.findall(r"([\w.\-]+)\s*=\s*\"([^\"]*)\"", value):
*parents, last = k.split(".")
target = item
for parent in parents:
target = target.setdefault(parent, {})
target[last] = v
table[key] = item
else:
string = re.match(r"\"([^\"]*)\"", value)
if string:
table[key] = string.group(1)
return data
def _resolve_version(raw: str, texts: list[str], properties: str,
catalog: dict[str, Any]) -> str | None:
"""A dependency version from a build file, following one variable."""
if "$" not in raw:
return raw
ref = re.fullmatch(r"\$\{libs\.versions\.([\w.]+)\.get\(\)\}", raw)
if ref:
for key, value in catalog["versions"].items():
if re.sub(r"[-_.]", ".", key) == ref.group(1):
return _catalog_version(value, {})
return None
var = re.fullmatch(r"\$\{?([A-Za-z_]\w*)\}?", raw)
if not var:
return None
name = re.escape(var.group(1))
value = r"[\"']([^\"'$]+)[\"']"
patterns = (
rf"\b(?:val|var|def)\s+{name}\b(?:\s*:\s*String)?\s*=\s*{value}",
rf"\bext\.{name}\s*=\s*{value}",
rf"\bextra\[\s*\"{name}\"\s*\]\s*=\s*{value}",
rf"\bset\(\s*\"{name}\"\s*,\s*{value}\s*\)",
rf"(?m)^\s*{name}\s*=\s*{value}",
)
for text in texts:
for pattern in patterns:
hit = re.search(pattern, text)
if hit:
return hit.group(1)
hit = re.search(rf"(?m)^\s*{name}\s*[=:]\s*([^\s#]+)", properties)
return hit.group(1) if hit else None
def detect_runtime(project: dict[str, Any]) -> dict[str, Any]:
"""Where the app gets LiteRT and the Google Tensor dispatch library."""
root = project["root"]
catalog = project["catalog"]
root_text = next(
(m["text"] for m in project["modules"] if m["dir"] == root), "")
found: dict[str, Any] = {"runtime": [], "core": [], "local_aars": [],
"so_files": []}
for module in project["modules"]:
text = module["text"]
for key, artifact in (("runtime", RUNTIME_ARTIFACT),
("core", CORE_ARTIFACT)):
coordinate = re.compile(rf"[\"']{re.escape(LITERT_MAVEN_GROUP)}:"
rf"{re.escape(artifact)}:([^\"']+)[\"']")
for m in coordinate.finditer(text):
found[key].append({
"module": module["rel"],
"declared": f"{LITERT_MAVEN_GROUP}:{artifact}:{m.group(1)}",
"version": _resolve_version(m.group(1), [text, root_text],
project["properties"], catalog),
})
for alias, lib in catalog["libraries"].items():
if (lib["group"], lib["name"]) != (LITERT_MAVEN_GROUP, artifact):
continue
accessor = "libs." + re.sub(r"[-_.]", ".", alias)
if re.search(rf"\b{re.escape(accessor)}(?:\.asProvider\(\))?"
r"(?![\w.])", text):
found[key].append({
"module": module["rel"],
"declared": f"{accessor} (gradle/libs.versions.toml)",
"version": lib["version"],
})
for m in re.finditer(
rf"[\"']([^\"']*{RUNTIME_ARTIFACT}[^\"']*\.aar)[\"']", text):
found["local_aars"].append({"module": module["rel"],
"path": m.group(1)})
for path in project["so_files"]:
found["so_files"].append({"path": _rel(path, root),
"sha256": _sha256(path),
"size_bytes": path.stat().st_size})
return found
def runtime_delivery(project: dict[str, Any],
runtime: dict[str, Any]) -> list[dict[str, Any]]:
"""Modules holding the runtime, with the device groups they target."""
root = project["root"]
holders = {r["module"] for r in runtime["runtime"] + runtime["local_aars"]}
for so in runtime["so_files"]:
path = root / so["path"]
owners = [m for m in project["modules"] if m["dir"] in path.parents]
if owners:
holders.add(max(owners, key=lambda m: len(m["dir"].parts))["rel"])
result = []
for module in project["modules"]:
if module["rel"] not in holders:
continue
manifest = module["dir"] / "src" / "main" / "AndroidManifest.xml"
groups: list[str] = []
try:
tree = ET.parse(manifest).getroot()
groups = [g.get(f"{{{DIST_NS}}}name")
for g in tree.iter(f"{{{DIST_NS}}}device-group")]
except (OSError, ET.ParseError):
pass
result.append({"module": module["rel"],
"manifest": _rel(manifest, root), "groups": groups})
return result
def find_loader(project: dict[str, Any],
pack_name: str) -> dict[str, Any] | None:
"""The app's TensorModelLoader (written by this skill) for the pack."""
for path, text in project["sources"]:
if "PACKAGED_SOC_MODELS" not in text:
continue
loader: dict[str, Any] = {"file": _rel(path, project["root"])}
for key, pattern in _LOADER_CONSTS.items():
m = pattern.search(text)
loader[key] = m.group(1) if m else None
if loader["pack"] not in (None, pack_name):
continue
m = _LOADER_SOCS_RE.search(text)
loader["socs"] = re.findall(r"\"([^\"]+)\"", m.group(1)) if m else None
return loader
return None
def locate_cpu_models(project: dict[str, Any], pack: dict[str, Any],
prefix: str, file_rel: str, default_group: str,
loader: dict[str, Any] | None, args: argparse.Namespace
) -> tuple[list[pathlib.Path], str]:
"""The app's uncompiled copies of the model, and where they live."""
root = project["root"]
if args.cpu_asset:
if args.cpu_asset.lower() == "none":
return [], "none"
path = pathlib.Path(args.cpu_asset).expanduser()
path = (path if path.is_absolute() else root / path).resolve()
if root not in path.parents or not path.is_file():
raise PackError(
2, f"--cpu-asset {args.cpu_asset}: no such file in {root}.")
return [path], "custom"
in_pack = pack["assets"] / f"{prefix}#group_{default_group}" / file_rel
stem = pathlib.PurePosixPath(file_rel).stem
names = [f"litert/{stem}_cpu_gpu.tflite"]
if loader and loader.get("cpu_asset") and loader["cpu_asset"] not in names:
names.insert(0, loader["cpu_asset"])
in_base = []
for module in project["modules"]:
if module is pack["module"]:
continue
for name in names:
path = module["dir"] / "src" / "main" / "assets" / name
if path.is_file() and path not in in_base:
in_base.append(path)
found = ([in_pack] if in_pack.is_file() else []) + in_base
if not found:
seen = []
for module in project["modules"]:
assets = module["dir"] / "src" / "main" / "assets"
if module is pack["module"] or not assets.is_dir():
continue
for here, _, files in _walk(assets, max_depth=4):
seen += [_rel(here / f, root) for f in files if f.endswith(".tflite")]
hint = (f" Models in the app's assets: {', '.join(seen[:5])}."
if seen else "")
raise PackError(
2,
"cannot tell where the app keeps the original (CPU) model of "
f"{prefix}/{file_rel}: it is neither in {_rel(in_pack, root)} nor at "
f"<module>/src/main/assets/{names[-1]}.{hint} Pass --cpu-asset "
"<path in the project>, or --cpu-asset none if the app keeps no "
"CPU copy.",
)
if in_pack.is_file():
return found, "pack+base" if in_base else "pack"
return found, "base"
def _file_entry(root: pathlib.Path, path: pathlib.Path, role: str,
soc: str | None, group: str | None, new: dict[str, Any],
old_scan: dict[str, Any] | None = None) -> dict[str, Any]:
"""Update-plan entry for one project file: its action, old and new model."""
if old_scan is None and path.is_file():
old_scan = scan_model(path)
old = None
if old_scan:
old = {key: old_scan.get(key) for key in (
"sha256", "size_bytes", "compiled", "soc_models", "legacy_ops")}
if old is None:
action = "add"
elif old["sha256"] == new["sha256"]:
action = "unchanged"
else:
action = "replace"
return {
"path": _rel(path, root),
"role": role,
"soc": soc,
"group": group,
"action": action,
"source": str(new["path"]),
"new": {"sha256": new["sha256"], "size_bytes": new["size_bytes"]},
"old": old,
}
def _verdict(files: list[dict[str, Any]], edits: list[dict[str, Any]]) -> str:
if edits:
return "structural"
if all(f["action"] == "unchanged" for f in files):
return "up-to-date"
return "drop-in"
def _socs_text(socs) -> str:
return ", ".join(soc_display(s) for s in socs) or "none"
def plan_update(args: argparse.Namespace, builds: dict[str, dict[str, Any]],
fallback: dict[str, Any], project: dict[str, Any],
pins: dict[str, Any], notes: list[str]) -> dict[str, Any]:
"""What to copy into the app, and what else the update needs."""
root = project["root"]
if project["catalog_error"]:
notes.append(project["catalog_error"] + ".")
packs = find_packs(project)
dtcs = find_dtcs(project)
for d in dtcs:
if d["groups"] is None:
notes.append(f"{d['module']['build_file']} names the device-targeting "
f"config {d['rel']}, which does not exist.")
usable = [d for d in dtcs if d["groups"] is not None]
# 1. The AI pack with the Google Tensor builds.
candidates = []
for pack in packs:
app = app_module_for(pack, project, args)
own = [d for d in usable if app is not None and d["module"] is app]
dtc = own[0] if own else (usable[0] if len(usable) == 1 else None)
groups = dtc["groups"] if dtc else {}
tensor = any(group_soc(groups.get(g["group"])) for g in pack["group_dirs"])
if not tensor and dtc is None:
tensor = any(_stamped_socs(g["dir"]) for g in pack["group_dirs"])
if tensor:
candidates.append((pack, app, dtc))
if not candidates:
raise PackError(
2,
f"no AI pack with Google Tensor builds in {root} (looked for modules "
"with an aiPack or assetPack block and src/main/assets/<folder>"
"#group_<device group>/ folders). If the app has no Google Tensor "
"setup yet, this is a new integration: run without --update-project "
"and follow INTEGRATION.md.",
)
listed = ", ".join(f"{p['name']} ({p['module']['rel']})"
for p, _, _ in candidates)
if args.pack_name:
candidates = [c for c in candidates if args.pack_name in (
c[0]["name"], c[0]["module"]["dir"].name)]
if not candidates:
raise PackError(
2,
f"--pack-name {args.pack_name}: no AI pack with Google Tensor "
f"builds has that name. Found: {listed}.",
)
if len(candidates) > 1:
raise PackError(
2,
f"several AI packs ship Google Tensor builds: {listed}. Pass "
"--pack-name to pick one.",
)
pack, app, dtc = candidates[0]
dtc_groups = dtc["groups"] if dtc else {}
dtc_rel = dtc["rel"] if dtc else None
default_group = "other"
if app:
m = _DEFAULT_GROUP_RE.search(app["text"])
default_group = m.group(1) if m else default_group
delivery = pack["delivery"]
if "delivery" in args.explicit:
if delivery and args.delivery != delivery:
raise PackError(
2,
f"the AI pack {pack['name']} uses {delivery} delivery "
f"({pack['module']['build_file']}), and --update-project keeps it. "
"Drop --delivery, or change deliveryType there first.",
)
if not delivery:
delivery = args.delivery
notes.append(f"no deliveryType in {pack['module']['build_file']}; "
f"UPDATE.md assumes --delivery {delivery}.")
# 2. The model in the pack: <prefix>#group_<group>/<file>.
models: dict[tuple[str, str], int] = {}
for g in pack["group_dirs"]:
if g["group"] == default_group:
continue
for here, _, files in _walk(g["dir"], max_depth=3):
for name in files:
if name.endswith(".tflite"):
key = (g["prefix"], _rel(here / name, g["dir"]))
models[key] = models.get(key, 0) + 1
shown = ", ".join(f"{p}/{f}" for p, f in models) or "none"
keys = list(models)
if args.model_name:
want = args.model_name
want = want[: -len(".tflite")] if want.endswith(".tflite") else want
keys = [k for k in keys if pathlib.PurePosixPath(k[1]).stem == want]
if not keys:
raise PackError(
2,
f"--model-name {args.model_name}: no such model in the AI pack "
f"{pack['name']}. Found: {shown}.",
)
if len(keys) > 1:
raise PackError(
2,
f"the AI pack {pack['name']} holds several models: {shown}. Pass "
"--model-name to pick one.",
)
if not keys:
raise PackError(
2, f"the AI pack {pack['name']} has no .tflite in its device-group "
"folders.")
prefix, file_rel = keys[0]
model_path = f"{prefix}/{file_rel}"
# 3. Its device groups, matched to SoCs by the XML (else by the stamps).
by_group = {}
for g in pack["group_dirs"]:
if g["prefix"] != prefix or g["group"] == default_group:
continue
name = g["group"]
current = g["dir"] / file_rel
scan = scan_model(current) if current.is_file() else None
stamp = (scan["soc_models"][0] if scan and scan["compiled"]
and len(scan["soc_models"]) == 1 else None)
if name in dtc_groups:
soc = group_soc(dtc_groups[name])
if soc == "several":
socs = ", ".join(f"{a} {b}" for a, b in dtc_groups[name]["socs"])
raise PackError(
2,
f"device group {name} in {dtc_rel} selects several SoCs "
f"({socs}), but a compiled build runs on one SoC only. Give "
"each SoC its own group (as LiteRT's exporter does), then re-run.",
)
if soc and stamp and stamp != soc:
notes.append(
f"{_rel(current, root)} is stamped {stamp}, but group {name} "
f"selects {soc_display(soc)}: those phones get the wrong build "
f"today. The update puts the {soc} build there.")
else:
soc = stamp
if dtc:
notes.append(f"group {name} is not defined in {dtc_rel}; bundletool "
"rejects bundles whose folders use undefined groups.")
by_group[name] = {"dir": g["dir"], "soc": soc, "current": current,
"scan": scan}
managed = {n: i for n, i in by_group.items()
if i["soc"] in SUPPORTED_TARGETS}
others = {n: i for n, i in by_group.items() if n not in managed}
by_soc: dict[str, list[str]] = {}
for name, info in managed.items():
by_soc.setdefault(info["soc"], []).append(name)
for soc, names in by_soc.items():
if len(names) > 1:
raise PackError(
2,
f"device groups {', '.join(names)} all hold {soc_display(soc)} "
"builds; keep one group per SoC, then re-run.",
)
# 4. The files to copy.
files: list[dict[str, Any]] = []
groups_out: list[dict[str, Any]] = []
added: list[dict[str, Any]] = []
for soc, build in builds.items():
if soc in by_soc:
name = by_soc[soc][0]
info = managed[name]
files.append(_file_entry(root, info["current"], "tensor", soc, name,
build, info["scan"]))
groups_out.append({"group": name, "soc": soc,
"action": files[-1]["action"]})
continue
defined = [n for n, g in dtc_groups.items() if group_soc(g) == soc]
if len(defined) > 1:
raise PackError(
2,
f"device groups {', '.join(defined)} in {dtc_rel} all select "
f"{soc_display(soc)}; keep one group per SoC, then re-run.",
)
name = defined[0] if defined else group_of(soc)
if not defined and name in dtc_groups:
raise PackError(
2,
f"{dtc_rel} already defines a group {name} that does not select "
f"{soc_display(soc)}; rename that group, then re-run.",
)
path = pack["assets"] / f"{prefix}#group_{name}" / file_rel
files.append(_file_entry(root, path, "tensor", soc, name, build))
groups_out.append({"group": name, "soc": soc, "action": "add"})
added.append({"soc": soc, "group": name, "defined": bool(defined)})
removed = [{"soc": i["soc"], "group": n, "dir": _rel(i["dir"], root)}
for n, i in managed.items() if i["soc"] not in builds]
for r in removed:
groups_out.append({"group": r["group"], "soc": r["soc"],
"action": "no new build"})
for name, info in others.items():
groups_out.append({"group": name, "soc": info["soc"],
"action": "kept (not a SoC this skill compiles for)"})
# The optional quick-test copies (<app module>/tensor_quick_test/<SoC>/).
if app is not None and (app["dir"] / APP_QUICK_TEST_DIR).is_dir():
quick_dir = app["dir"] / APP_QUICK_TEST_DIR
for soc, build in builds.items():
path = quick_dir / soc / "assets" / model_path
if path.is_file():
files.append(dict(_file_entry(root, path, "tensor", soc, None, build),
quick_test=True))
stale = sorted(p.name for p in quick_dir.iterdir()
if p.name not in builds
and (p / "assets" / model_path).is_file())
if stale:
notes.append(f"{_rel(quick_dir, root)}/ also holds builds for "
f"{', '.join(stale)}, which get no new build: quick tests "
"on those phones keep the previous model.")
loader = find_loader(project, pack["name"])
cpu_paths, layout = locate_cpu_models(project, pack, prefix, file_rel,
default_group, loader, args)
for path in cpu_paths:
files.append(_file_entry(root, path, "cpu", None, None, fallback))
old = files[-1]["old"]
if old and old["compiled"]:
notes.append(f"{files[-1]['path']} holds a compiled build today, which "
"the CPU cannot run; the update puts the original there.")
elif old and old["legacy_ops"]:
notes.append(f"{files[-1]['path']} holds a model compiled by another "
"toolchain today (Edge TPU custom op), which the CPU "
"cannot run; the update puts the original there.")
for f in files:
if f["role"] == "tensor" and f["old"] and f["old"]["legacy_ops"]:
notes.append(f"{f['path']} holds a build from another toolchain today "
"(Edge TPU custom op); the update replaces it with the "
"LiteRT build.")
# 5. Checks, and the changes the project needs besides the files.
edits: list[dict[str, Any]] = []
checks: list[dict[str, Any]] = []
def edit(kind: str, file: str | None, summary: str,
snippet: str | None = None, lang: str = "", **extra) -> None:
edits.append(dict(kind=kind, file=file, summary=summary,
snippet=snippet, lang=lang, **extra))
def check(name: str, status: str, detail: str) -> None:
checks.append({"check": name, "status": status, "detail": detail})
app_socs = sorted(i["soc"] for i in managed.values())
if added or removed:
check("SoCs", "edit", f"the app ships {_socs_text(app_socs)}; new builds "
f"for {_socs_text(builds)}")
else:
check("SoCs", "pass", f"the app ships {_socs_text(app_socs)}, and each "
"has a new build")
check("Names", "pass", f"kept: pack `{pack['name']}`, `{model_path}`, "
+ ", ".join(f"{soc_display(g['soc'])} in `{g['group']}`"
for g in groups_out if g["soc"] in builds))
if cpu_paths:
copies = ", ".join(f"`{_rel(p, root)}`" for p in cpu_paths)
if all(f["action"] == "unchanged" for f in files if f["role"] == "cpu"):
check("CPU model", "pass", f"{copies} already holds the original the "
"new builds were compiled from")
else:
check("CPU model", "pass", f"{copies} gets the new original, so the "
"CPU path runs the same model as the Tensor builds")
else:
check("CPU model", "info", "none (--cpu-asset none): phones outside the "
"Google Tensor groups, and failed TPU loads, have no model")
runtime = detect_runtime(project)
delivered_by = runtime_delivery(project, runtime)
pinned = pins.get("maven_release")
rt_versions = sorted({r["version"] or "unknown" for r in runtime["runtime"]})
core_versions = sorted({r["version"] or "unknown" for r in runtime["core"]})
if runtime["runtime"]:
if rt_versions == [pinned]:
check("Runtime", "pass", f"`{RUNTIME_ARTIFACT}` {pinned}, the release "
"this skill pins")
required = False
reason = ("the app uses the release this skill pins, but the library "
"in that Maven artifact is a different build than the "
"benchmark's default download.")
elif "unknown" in rt_versions:
declared = ", ".join(sorted({f"`{r['declared']}`"
for r in runtime["runtime"]}))
check("Runtime", "device", f"the version of `{RUNTIME_ARTIFACT}` "
f"could not be read from {declared}")
required = True
reason = "the version of the app's Google Tensor runtime is unknown."
else:
check("Runtime", "device", f"the app uses `{RUNTIME_ARTIFACT}` "
f"{', '.join(rt_versions)}; this skill pins "
f"{pinned or 'an unknown release'}")
required = True
reason = (f"the app uses `{RUNTIME_ARTIFACT}` {', '.join(rt_versions)}"
f", not the release this skill pins ({pinned}).")
known_core = [v for v in core_versions if v != "unknown"]
known_rt = [v for v in rt_versions if v != "unknown"]
if known_core and known_rt and known_core != known_rt:
edit("runtime-versions", None,
f"`{LITERT_MAVEN_GROUP}:litert` is {', '.join(known_core)} but "
f"`{RUNTIME_ARTIFACT}` is {', '.join(known_rt)}: use one release "
"for both.")
elif "unknown" in core_versions + rt_versions:
notes.append(f"some LiteRT versions could not be read from the build "
f"files; {LITERT_MAVEN_GROUP}:litert and {RUNTIME_ARTIFACT} "
"must be one release.")
elif runtime["so_files"] or runtime["local_aars"]:
where = ([s["path"] for s in runtime["so_files"]]
+ [a["path"] for a in runtime["local_aars"]])
check("Runtime", "device", "the app bundles the Google Tensor library "
"itself (" + ", ".join(f"`{w}`" for w in where) + "); its release "
"is unknown")
required = True
reason = "the release of the Google Tensor library in the app is unknown."
else:
check("Runtime", "edit", "no Google Tensor NPU runtime in the project")
edit("runtime-missing", None,
f"No Google Tensor NPU runtime found (`{LITERT_MAVEN_GROUP}:"
f"{RUNTIME_ARTIFACT}` or `{DISPATCH_LIB_NAME}`), so the app cannot "
"use the TPU. Add it as INTEGRATION.md describes: run "
"package_ai_pack.py without --update-project to get the runtime "
"module.")
required = True
reason = ("the app has no Google Tensor runtime yet (section 2): test "
"with the release this skill pins.")
for a in added:
soc, name = a["soc"], a["group"]
if not a["defined"]:
if dtc:
edit("device-group", dtc_rel,
f"Define the device group `{name}` for {soc_display(soc)}: add "
"this element inside `<config:device-targeting-config>`.",
DTC_GROUP_SNIPPET.format(group=name, model=soc_display(soc)),
"xml", group=name)
else:
edit("device-group", None,
f"The app has no device-targeting config, which the group "
f"`{name}` needs: see step 2 of INTEGRATION.md (run "
"package_ai_pack.py without --update-project to get it).")
for module in delivered_by:
if module["groups"] and name not in module["groups"]:
edit("runtime-groups", module["manifest"],
f"Deliver the runtime to `{name}` too: add this line next to "
"the other `<dist:device-group>` elements.",
f'<dist:device-group dist:name="{name}"/>', "xml")
users = []
for other_pack in packs:
for g in other_pack["group_dirs"]:
label = f"{_rel(other_pack['assets'], root)}/{g['prefix']}#group_*"
if (other_pack is not pack or g["prefix"] != prefix) and (
label not in users):
users.append(label)
if added and users:
edit("other-group-folders", None,
"These folders also use device groups and need a variant for "
+ ", ".join(f"`{a['group']}`" for a in added) + " too (bundletool "
"requires the same groups everywhere): "
+ ", ".join(f"`{u}`" for u in users) + ".")
for r in removed:
soc, name = r["soc"], r["group"]
edit("no-new-build", r["dir"],
f"`{name}` ({soc_display(soc)}) gets no new build, so those phones "
f"would keep the previous model. Compile one (`compile_model.py "
f"--target {soc}`) and re-run with it, or remove "
f"{soc_display(soc)} from the app: delete `{r['dir']}/` (and the "
f"`#group_{name}` folders of other packs), the `{name}` group in "
f"`{dtc_rel or 'the device-targeting config'}`, its "
"`<dist:device-group>` line in the runtime module's manifest, and "
f"\"{soc_display(soc)}\" from the loader's SoC list.")
holding = [n for n, i in others.items() if i["current"].is_file()]
if holding:
edit("other-socs", None,
"Groups " + ", ".join(f"`{n}`" for n in holding) + " are for SoCs "
"this skill does not compile for and still hold the previous model: "
"rebuild them with their vendor's tools, or phones will run "
"different models.")
cpu_files = [f for f in files if f["role"] == "cpu"]
if not cpu_files:
check("Model inputs/outputs", "unknown", "the app keeps no uncompiled "
"copy to compare with; compare your code with model_io.json")
elif all(f["action"] == "unchanged" for f in cpu_files):
check("Model inputs/outputs", "pass", "same original model as the app's "
"(SHA-256 match)")
else:
check("Model inputs/outputs", "unknown", "compared in a real run (it "
"needs ai-edge-litert)")
new_socs = [soc_display(s) for s in builds]
if loader:
if loader["model_path"] and loader["model_path"] != model_path:
notes.append(f"{loader['file']} opens {loader['model_path']}, but the "
f"pack's model is {model_path}.")
if loader["socs"] is not None and sorted(loader["socs"]) != new_socs:
soc_list = ", ".join(f'"{s}"' for s in new_socs)
edit("loader", loader["file"],
"Make the loader's SoC list match the new builds:",
f"val PACKAGED_SOC_MODELS: Set<String> = setOf({soc_list})",
"kotlin")
check("Loader", "edit", f"`{loader['file']}` lists "
f"{', '.join(loader['socs']) or 'no SoC'}")
else:
check("Loader", "pass", f"`{loader['file']}` (TensorModelLoader) "
"lists the same SoCs")
else:
detail = ("no TensorModelLoader found; the app's own loading code stays "
"as it is")
readers = [_rel(p, root) for p, text in project["sources"]
if "Build.SOC_MODEL" in text]
if added and readers:
detail += ("; check " + ", ".join(f"`{r}`" for r in readers[:3])
+ ": they read Build.SOC_MODEL")
check("Loader", "info", detail)
if delivery:
check("Delivery", "info", f"`{delivery}` (kept). "
f"{DELIVERY_UPDATE[delivery]}")
else:
check("Delivery", "unknown", "no deliveryType in "
f"`{pack['module']['build_file']}`")
unverified = [s for s, b in builds.items()
if (b.get("sidecar") or {}).get("input_sha256")
!= fallback["sha256"]]
if unverified:
check("Provenance", "info", "not verifiable for " + ", ".join(unverified)
+ " (no .compile.json, or compiled from another file)")
else:
check("Provenance", "pass", "every build was compiled from --fallback "
"(its .compile.json)")
app_info = None
if app:
code = _VERSION_CODE_RE.search(app["text"])
app_id = _APP_ID_RE.search(app["text"])
app_info = {
"module": app["rel"],
"gradle_path": app["gradle_path"] or ":" + app["rel"].replace(
"/", ":"),
"build_file": app["build_file"],
"version_code": int(code.group(1)) if code else None,
"application_id": app_id.group(1) if app_id else None,
}
else:
notes.append(f"no module lists the AI pack {pack['name']} in assetPacks; "
"pass --app-module to name the app module.")
libraries = []
if app_info:
task = _bundle_task(app_info)
libraries.append(
f"the app bundle, which holds the library exactly as the app ships "
f"it: `{root / _bundle_path(app_info)}` (build it in the project "
f"with `./gradlew {task}`)")
known = [v for v in rt_versions if v != "unknown"]
if not runtime["runtime"] and not runtime["so_files"] and pinned:
known = [pinned]
for version in known:
libraries.append(f"the Maven AAR at {version}, downloaded from "
f"{RUNTIME_AAR_URL.format(release=version)}")
libraries += [f"`{root / s['path']}`" for s in runtime["so_files"]]
libraries += [f"`{a['path']}` (declared in `{a['module']}`)"
for a in runtime["local_aars"]]
return {
"project": str(root),
"pack": {
"name": pack["name"],
"module": pack["module"]["rel"],
"gradle_path": pack["module"]["gradle_path"],
"build_file": pack["module"]["build_file"],
"kind": pack["kind"],
"delivery": delivery,
},
"model_path": model_path,
"default_group": default_group,
"device_targeting_config": dtc_rel,
"app_module": app_info,
"cpu_layout": layout,
"groups": groups_out,
"files": files,
"edits": edits,
"checks": checks,
"runtime": {
"pinned_maven_release": pinned,
"maven": runtime["runtime"],
"litert": runtime["core"],
"so_files": runtime["so_files"],
"local_aars": runtime["local_aars"],
"delivered_by": delivered_by,
},
"loader": loader,
"device_check": {
"required": required,
"reason": reason,
"libraries": libraries,
"builds": [[soc, str(b["path"])] for soc, b in builds.items()],
},
"pins": pins,
"verdict": _verdict(files, edits),
}
def _bundle_task(app: dict[str, Any]) -> str:
path = app["gradle_path"].rstrip(":")
return f"{path}:bundleRelease"
def _bundle_path(app: dict[str, Any]) -> str:
last = app["gradle_path"].strip(":").split(":")[-1] or "app"
base = "" if app["module"] == "." else app["module"] + "/"
return f"{base}build/outputs/bundle/release/{last}-release.aab"
def compare_io(old: dict[str, Any],
new: dict[str, Any]) -> tuple[str, str, list[str]]:
"""(status, detail, changes) between the app's model and the new one."""
for data, who in ((old, "the app's model"), (new, "the new model")):
if data.get("error"):
return "unknown", f"could not read {who} ({data['error']})", []
before = {s["key"]: s for s in old["signatures"]}
after = {s["key"]: s for s in new["signatures"]}
changes: list[str] = []
renamed: list[str] = []
for key in sorted(set(before) | set(after)):
label = f"signature '{key}'" if key else "model"
if key not in after or key not in before:
changes.append(f"{label}: {'removed' if key not in after else 'new'}")
continue
for side in ("inputs", "outputs"):
a = {t["name"]: t for t in before[key][side]}
b = {t["name"]: t for t in after[key][side]}
if set(a) == set(b):
pairs = [(a[n], b[n]) for n in a]
elif len(a) == len(b):
pairs = list(zip(before[key][side], after[key][side]))
renamed += [f"{x['name']} -> {y['name']}" for x, y in pairs
if x["name"] != y["name"]]
else:
changes.append(f"{label}: {len(a)} {side} -> {len(b)}")
continue
for x, y in pairs:
if (x["shape"], x["dtype"]) != (y["shape"], y["dtype"]):
changes.append(f"{label} {side[:-1]} {y['name']}: {x['dtype']} "
f"{x['shape']} -> {y['dtype']} {y['shape']}")
if changes:
return "edit", "; ".join(changes), changes
if renamed:
return ("info", "same shapes and types, but tensor names changed ("
+ "; ".join(renamed) + "): code that uses names needs the new "
"ones", [])
return "pass", "same inputs and outputs (names, shapes and types)", []
def resolve_update_output(args: argparse.Namespace, fallback: dict[str, Any],
pack_name: str) -> tuple[pathlib.Path, str | None]:
"""Output directory of the update plan, and a note for a dry run."""
if args.output_dir:
out = pathlib.Path(args.output_dir).expanduser().resolve()
else:
safe = re.sub(r"[^\w.\-]", "_", pack_name)
out = fallback["path"].parent / "app_update" / safe
if not out.exists():
return out, None
if not _written_by_us(out):
raise PackError(
2,
f"refusing to replace {out}: it is not empty and was not written by "
"package_ai_pack.py. Choose another --output-dir.",
)
if args.overwrite:
return out, "replacing it"
if args.dry_run:
return out, "exists: a real run needs --overwrite"
raise PackError(
2,
f"output already exists: {out}. Choose another --output-dir, or pass "
"--overwrite to replace an update written by this script.",
)
def _exported_group(dtc_text: str, group: str) -> str | None:
"""The exporter's <config:device-group> element for ``group``."""
m = re.search(rf'(?ms)^([ \t]*)(<config:device-group name="'
rf'{re.escape(group)}">.*?</config:device-group>)', dtc_text)
if not m:
return None
indent = m.group(1)
lines = m.group(2).splitlines()
return "\n".join(
[lines[0]] + [x[len(indent):] if x.startswith(indent) else x
for x in lines[1:]])
def verify_update(stage: pathlib.Path, plan: dict[str, Any],
root: pathlib.Path) -> list[str]:
"""Checks the staged files against the plan and the project."""
def fail(message: str):
raise PackError(7, f"update verification failed: {message}")
passed: list[str] = []
planned = set()
for item in plan["files"]:
if item["action"] == "unchanged":
continue
staged = stage / "files" / item["path"]
planned.add(staged)
if not staged.is_file():
fail(f"missing files/{item['path']}.")
got = scan_model(staged)
if got["sha256"] != item["new"]["sha256"]:
fail(f"files/{item['path']} is not byte-identical to {item['source']}.")
if item["role"] == "tensor" and (
not got["compiled"] or got["soc_models"] != [item["soc"]]):
fail(f"files/{item['path']} is not stamped {item['soc']}.")
if item["role"] == "cpu" and got["compiled"]:
fail(f"files/{item['path']} is a compiled build, but the app runs it "
"on the CPU.")
current = root / item["path"]
if item["action"] == "replace":
if (not current.is_file()
or _sha256(current) != item["old"]["sha256"]):
fail(f"{item['path']} changed in the project while the update was "
"prepared; re-run.")
elif current.exists():
fail(f"{item['path']} appeared in the project while the update was "
"prepared; re-run.")
kind = (f"stamped {item['soc']}" if item["role"] == "tensor"
else "uncompiled")
passed.append(f"files/{item['path']}: byte-identical to "
f"{pathlib.Path(item['source']).name}, {kind}")
files_dir = stage / "files"
staged_files = set(files_dir.rglob("*")) if files_dir.is_dir() else set()
extra = sorted(_rel(p, stage) for p in staged_files
if p.is_file() and p not in planned)
if extra:
fail(f"unexpected files in the update: {extra}.")
return passed
def update_doc_values(summary: dict[str, Any]) -> dict[str, str]:
"""Values for assets/templates/UPDATE.md."""
pack, app = summary["pack"], summary["app_module"]
pins = summary["pins"]
def cell(text) -> str:
return str(text).replace("|", "\\|")
def state(info: dict[str, Any] | None) -> str:
if not info:
return "-"
return f"{fmt_size(info['size_bytes'])}, `{info['sha256'][:12]}`"
rows = [f"| AI pack | `{pack['name']}` (`{pack['module']}`), "
f"`{pack['delivery'] or 'unknown'}` delivery |"]
for g in summary["groups"]:
label = soc_display(g["soc"]) if g["soc"] else "other SoC"
rows.append(f"| {label} | group `{g['group']}`: {g['action']} |")
cpu = [f for f in summary["files"] if f["role"] == "cpu"]
rows.append("| CPU model | " + (", ".join(
f"`{f['path']}`: {f['action']}" for f in cpu) or "none in the app")
+ " |")
runtime = next(c for c in summary["checks"] if c["check"] == "Runtime")
rows.append(f"| App runtime | {cell(runtime['detail'])} |")
table = ["| File in the project | Action | Now | New |", "|---|---|---|---|"]
for f in summary["files"]:
what = (f"{soc_display(f['soc'])} build" if f["role"] == "tensor"
else "CPU model")
if f.get("quick_test"):
what += ", quick test"
table.append(f"| `{f['path']}` | {f['action']} ({what}) | "
f"{state(f['old'])} | {state(f['new'])} |")
if summary["edits"]:
items = []
for i, e in enumerate(summary["edits"], 1):
where = f"**`{e['file']}`**: " if e["file"] else ""
item = f"{i}. {where}{e['summary']}"
if e.get("snippet"):
block = [f"```{e.get('lang') or ''}"] + e["snippet"].splitlines()
item += "\n\n" + "\n".join(
" " + x if x else "" for x in block + ["```"])
items.append(item)
edits = "\n\n".join(items)
else:
edits = ("None: the device groups, the runtime, the Gradle files and the "
"code stay as they are.")
checks = "\n".join(f"| {c['check']} | {c['status']} | {cell(c['detail'])} |"
for c in summary["checks"])
dc = summary["device_check"]
device = [("Required before release: " if dc["required"]
else "Recommended: ") + "run each new build with the Google "
f"Tensor library the app ships, because {dc['reason']}", "",
"```bash"]
for soc, path in dc["builds"]:
device += [f"# On a Pixel with {soc_display(soc)}:",
f"python3 {shlex.quote(str(BENCHMARK_SCRIPT))} "
f"--model {shlex.quote(path)} --dispatch-lib <LIBRARY>"]
device += ["```", "", "`<LIBRARY>` can be:", ""]
device += [f"- {option}" for option in dc["libraries"]] or ["- (none found)"]
device += ["", "If the strict NPU run fails with the app's library but "
"passes with the default download, upgrade "
f"`{LITERT_MAVEN_GROUP}:litert` and `{RUNTIME_ARTIFACT}` "
f"together to {pins.get('maven_release')} (Kotlin "
f"{pins.get('kotlin_min')} or newer)."]
first = next((g["group"] for g in summary["groups"]
if g["action"] in ("replace", "add", "unchanged")), "<group>")
if app:
bundle_task = _bundle_task(app)
bundle = _bundle_path(app)
code = app["version_code"]
version_step = (f"Raise `versionCode` in `{app['build_file']}`"
+ (f" (now {code})" if code is not None else "")
+ ": Google Play accepts a new app bundle only with a "
"higher one.")
else:
bundle_task = ":<app module>:bundleRelease"
bundle = "<app module>/build/outputs/bundle/release/<app>-release.aab"
version_step = ("Raise `versionCode` in the app module's build file: "
"Google Play accepts a new app bundle only with a higher "
"one.")
app_id = (app or {}).get("application_id") or "<your.application.id>"
commands = [
f"./gradlew {bundle_task}",
"java -jar bundletool-all.jar build-apks --local-testing --overwrite \\",
f" --bundle={bundle} --output=/tmp/app.apks",
f"adb uninstall {app_id}",
"java -jar bundletool-all.jar install-apks --apks=/tmp/app.apks \\",
f" --device-groups={first}",
]
if summary["loader"]:
commands.append("adb logcat -s LiteRtTensor # TensorModelLoader: "
"\"path\":\"npu\" or \"cpu\"")
delivery = pack["delivery"]
return {
"MODEL_PATH": summary["model_path"],
"GENERATED_AT": summary["generated_at"].replace("T", " "),
"PROJECT_DIR": summary["project"],
"VERDICT": VERDICTS[summary["verdict"]].capitalize(),
"SUMMARY_ROWS": "\n".join(rows),
"FILE_TABLE": "\n".join(table),
"EDITS": edits,
"CHECK_ROWS": checks,
"DEVICE_CHECK": "\n".join(device),
"VERSION_CODE_STEP": version_step,
"TEST_COMMANDS": "\n".join(" " + c for c in commands),
"DELIVERY_UPDATE": (DELIVERY_UPDATE[delivery] if delivery else
"Google Play updates the AI pack with the app."),
}
def build_update(plan: dict[str, Any], builds: dict[str, dict[str, Any]],
fallback: dict[str, Any], out: pathlib.Path,
versions: dict[str, Any], notes: list[str]) -> dict[str, Any]:
"""Writes the update plan into a staging directory, verifies it, moves it."""
root = pathlib.Path(plan["project"])
stage = out.parent / f".{out.name}.staging-{os.getpid()}"
if stage.exists():
shutil.rmtree(stage)
stage.mkdir(parents=True)
try:
export_dir = stage / ".export"
export_with_litert(builds, fallback, export_dir, EXPORT_PACK,
EXPORT_MODEL, versions.get("pip_release"))
assets = export_dir / EXPORT_PACK / "src" / "main" / "assets"
verification = check_exported_builds(stage, assets, EXPORT_MODEL, builds)
original = assets / OTHER_GROUP_DIR / f"{EXPORT_MODEL}.tflite"
if (not original.is_file()
or scan_model(original)["sha256"] != fallback["sha256"]):
_verify_fail("the exporter's copy of the original differs from "
"--fallback.")
dtc = export_dir / "device_targeting_configuration.xml"
verification.append(check_exported_dtc(dtc, builds))
dtc_text = dtc.read_text(encoding="utf-8")
for e in plan["edits"]:
if e["kind"] == "device-group" and e["snippet"]:
e["snippet"] = _exported_group(dtc_text, e["group"]) or e["snippet"]
for item in plan["files"]:
if item["action"] == "unchanged":
continue
dest = stage / "files" / item["path"]
dest.parent.mkdir(parents=True, exist_ok=True)
if item["role"] == "tensor":
source = (assets / f"model#group_{group_of(item['soc'])}"
/ f"{EXPORT_MODEL}.tflite")
else:
source = fallback["path"]
shutil.copyfile(source, dest)
shutil.rmtree(export_dir)
new_io = read_model_io(fallback["path"])
dump_model_io(new_io, stage / "model_io.json")
app_io = None
old = next((f for f in plan["files"] if f["role"] == "cpu"
and f["action"] == "replace" and not f["old"]["compiled"]),
None)
if old:
app_io = read_model_io(root / old["path"])
status, detail, changes = compare_io(app_io, new_io)
io_check = next(c for c in plan["checks"]
if c["check"] == "Model inputs/outputs")
io_check.update(status=status, detail=detail)
if changes:
plan["edits"].append({
"kind": "model-io", "file": None, "lang": "", "snippet": None,
"summary": "The model's inputs or outputs changed ("
+ "; ".join(changes) + "): update the code that fills "
"the inputs and reads the outputs (model_io.json "
"lists the new ones).",
})
plan["verdict"] = _verdict(plan["files"], plan["edits"])
verification += verify_update(stage, plan, root)
summary = {
"generator": GENERATOR,
"mode": "update",
"generated_at": datetime.datetime.now(datetime.timezone.utc)
.strftime("%Y-%m-%dT%H:%M:%SZ"),
**plan,
"model_io": {"new": new_io, "app": app_io},
"litert": {
"exporter": "ai_edge_litert.aot.ai_pack.export_lib",
"exporter_package": installed_litert(),
"pinned_pip_release": versions.get("pip_release"),
},
"verification": verification,
"notes": notes,
}
(stage / UPDATE_SUMMARY).write_text(
json.dumps(summary, indent=2) + "\n", encoding="utf-8")
(stage / "UPDATE.md").write_text(
render("UPDATE.md", update_doc_values(summary)), encoding="utf-8")
if out.exists():
shutil.rmtree(out)
out.parent.mkdir(parents=True, exist_ok=True)
os.replace(stage, out)
return summary
finally:
if stage.exists():
shutil.rmtree(stage, ignore_errors=True)
def print_update_plan(plan: dict[str, Any], out: pathlib.Path,
out_note: str | None, notes: list[str]) -> None:
"""Prints the dry-run plan of an update: files, verdict, edits, checks."""
pack = plan["pack"]
print("Dry run: inputs and project checked; nothing imported or written.")
print(f"Project: {plan['project']}")
print(f"AI pack: {pack['name']} ({pack['module']}, "
f"{pack['delivery'] or 'delivery unknown'}); the app opens "
f"{plan['model_path']}")
for f in plan["files"]:
old = fmt_size(f["old"]["size_bytes"]) if f["old"] else "new file"
print(f" {f['action']:<9} {f['path']} ({old} -> "
f"{fmt_size(f['new']['size_bytes'])}) <- {f['source']}")
print(f"Verdict: {VERDICTS[plan['verdict']]}")
for i, e in enumerate(plan["edits"], 1):
where = f"{e['file']}: " if e["file"] else ""
print(f" {i}. {where}{e['summary']}")
for line in (e.get("snippet") or "").splitlines():
print(f" {line}")
print("Checks:")
for c in plan["checks"]:
print(f" {c['status'].upper():<7} {c['check']}: {c['detail']}")
print(f"Would write: {out}" + (f" ({out_note})" if out_note else ""))
for note in notes:
print(f"NOTE: {note}")
def update_report_markdown(summary: dict[str, Any], out: pathlib.Path) -> str:
"""The Markdown summary printed after an update plan is written."""
pack = summary["pack"]
check = {c["check"]: c for c in summary["checks"]}
lines = [
f"**Update plan:** {out} ({VERDICTS[summary['verdict']]})",
f"**Project:** {summary['project']}; AI pack `{pack['name']}` "
f"(`{pack['module']}`, `{pack['delivery'] or 'unknown'}` delivery); "
f"the app opens `{summary['model_path']}`",
]
for f in summary["files"]:
old = fmt_size(f["old"]["size_bytes"]) if f["old"] else "new file"
lines.append(f"**{f['action'].capitalize()}:** `{f['path']}` ({old} -> "
f"{fmt_size(f['new']['size_bytes'])})")
edits = len(summary["edits"])
lines += [
"**Changes outside the model files:** "
+ (f"{edits} (UPDATE.md section 2)" if edits else "none"),
f"**App runtime:** {check['Runtime']['status']} - "
f"{check['Runtime']['detail']}",
"**Model inputs/outputs:** "
f"{check['Model inputs/outputs']['status']} - "
f"{check['Model inputs/outputs']['detail']}",
f"**Verified:** {len(summary['verification'])} checks passed "
"(update.json lists them)",
f"**Next:** {out / 'UPDATE.md'}",
]
return "\n".join(lines)
def main_update(args: argparse.Namespace, versions: dict[str, Any],
versions_error: str | None) -> int:
"""--update-project: plan (and with a real run, stage) the update."""
if "kotlin_package" in args.explicit:
raise PackError(
2, "--kotlin-package is not used with --update-project: the app's "
"own code is kept.")
if args.quick_test:
raise PackError(
2, f"--quick-test is not used with --update-project: an existing "
f"{APP_QUICK_TEST_DIR}/ folder of the app module is updated with the "
"other files.")
builds, fallback, notes = check_inputs(args)
try:
pins = {"maven_release": maven_release(versions, versions_error),
"kotlin_min": kotlin_min(versions, versions_error)}
except PackError:
if not args.dry_run:
raise
pins = {"maven_release": None, "kotlin_min": None}
project = inspect_project(args.update_project)
plan = plan_update(args, builds, fallback, project, pins, notes)
out, out_note = resolve_update_output(args, fallback, plan["pack"]["name"])
if args.dry_run:
if args.json:
print(json.dumps({"dry_run": True, "mode": "update",
"output_dir": str(out), "output_note": out_note,
**plan, "notes": notes}, indent=2))
else:
print_update_plan(plan, out, out_note, notes)
return 0
if not args.json:
print(f"Preparing the update of {plan['model_path']} in AI pack "
f"'{plan['pack']['name']}' with LiteRT's export_lib ...", flush=True)
summary = build_update(plan, builds, fallback, out, versions, notes)
if args.json:
print(json.dumps(dict(status="ok", output_dir=str(out), **summary),
indent=2))
else:
for note in summary["notes"]:
print(f"NOTE: {note}")
print()
print(update_report_markdown(summary, out))
return 0
# --------------------------------------------------------------------------
# Check mode (--check-project): is the app set up for a package?
# --------------------------------------------------------------------------
MIN_SDK = 31
MIN_AGP = (8, 10)
AGP_PLUGIN_IDS = ("com.android.application",)
AGP_CLASSPATH = "com.android.tools.build:gradle"
KOTLIN_PLUGIN_IDS = ("org.jetbrains.kotlin.android",)
KOTLIN_CLASSPATH = "org.jetbrains.kotlin:kotlin-gradle-plugin"
RUNTIME_MODULE_PATH = ":litert_npu_runtime_libraries:google_tensor_runtime"
STRINGS_MODULE_PATH = ":litert_npu_runtime_libraries:runtime_strings"
DOWNLOAD_PERMISSIONS = ("android.permission.FOREGROUND_SERVICE",
"android.permission.FOREGROUND_SERVICE_DATA_SYNC")
DEVICE_TARGETING_FLAG = "android.experimental.enableDeviceTargetingConfigApi"
_MIN_SDK_RE = re.compile(r"\bminSdk(?:Version)?\b\s*(?:=\s*|[ \t]+|\(\s*)(\d+)")
_LEGACY_PACKAGING_RE = re.compile(
r"\buseLegacyPackaging\b\s*(?:=\s*|[ \t]+)true")
_EXTRACT_LIBS_RE = re.compile(r"extractNativeLibs\s*=\s*\"true\"")
_ENABLE_SPLIT_RE = re.compile(r"\benableSplit\b\s*(?:=\s*|[ \t]+)true")
_KOTLIN_APPLIED_RE = re.compile(
r"org\.jetbrains\.kotlin\.android|kotlin\(\s*\"android\"\s*\)|"
r"[\"']kotlin-android[\"']|plugins\.kotlin\b|plugins\.jetbrains\.kotlin")
_PROJECT_DEP_RE = re.compile(
r"project\(\s*(?:path\s*[:=]\s*)?[\"'](:[\w.\-:]+)[\"']")
QUICK_TEST_BLOCK = {
True: (
'providers.gradleProperty("tensorQuickTest").orNull?.let { soc ->\n'
' android.sourceSets.getByName("debug")\n'
' .assets.srcDir("tensor_quick_test/$soc/assets")\n'
" dependencies.add(\n"
' "debugImplementation",\n'
' "com.google.ai.edge.litert:litert-npu-runtime-google-tensor:'
'{release}",\n'
" )\n"
"}"),
False: (
"def soc = providers.gradleProperty('tensorQuickTest').orNull\n"
"if (soc != null) {\n"
' android.sourceSets.debug.assets.srcDir("tensor_quick_test/$soc/'
'assets")\n'
" dependencies.add('debugImplementation',\n"
" 'com.google.ai.edge.litert:litert-npu-runtime-google-tensor:"
"{release}')\n"
"}"),
}
def _version_tuple(text: str) -> tuple[int, ...]:
return tuple(int(x) for x in re.findall(r"\d+", text)[:3])
_APP_PLUGIN_RE = re.compile(
r"com\.android\.application|android\.application(?![\w.])")
_APPLY_FALSE_RE = re.compile(r"[^\n]*?\bapply\s*\(?\s*false\b")
_ABI_RE = re.compile(r"[\"'](arm64-v8a|armeabi-v7a|armeabi|x86_64|x86|"
r"riscv64|mips64|mips)[\"']")
RUNTIME_ABI = "arm64-v8a" # the only ABI of the Google Tensor runtime AAR
def applies_app_plugin(text: str) -> bool:
"""True if a build file applies the Android application plugin.
A root build file that only declares it (``... apply false``) does not.
Args:
text: The build file's source.
Returns:
Whether the build file applies the plugin.
"""
return any(not _APPLY_FALSE_RE.match(text, m.end())
for m in _APP_PLUGIN_RE.finditer(text))
def abi_filters(text: str) -> set[str] | None:
"""The ABIs a build file's abiFilters name, or None if it sets none."""
found = None
for m in re.finditer(r"\babiFilters\b", text):
end = text.find("}", m.end())
found = (found or set()) | set(
_ABI_RE.findall(text[m.end():None if end < 0 else end]))
return found
def plugin_version(project: dict[str, Any], plugin_ids: tuple[str, ...],
classpath: str) -> tuple[str | None, str | None]:
"""(version, where) of a Gradle plugin: catalog, plugins {}, classpath."""
for plugin in project["catalog"]["plugins"].values():
if plugin["id"] in plugin_ids and plugin["version"]:
return plugin["version"], "gradle/libs.versions.toml"
sources = [(project["settings_rel"], project["settings_text"])] + [
(m["build_file"], m["text"]) for m in project["modules"]]
for where, text in sources:
for plugin_id in plugin_ids:
m = re.search(rf"\bid\s*\(?\s*[\"']{re.escape(plugin_id)}[\"']\s*\)?"
r"\s*version\s*\(?\s*[\"']([^\"'$]+)[\"']", text)
if m:
return m.group(1), where
if "org.jetbrains.kotlin.android" in plugin_ids:
m = re.search(r"\bkotlin\s*\(\s*\"android\"\s*\)\s*version\s*"
r"\"([^\"$]+)\"", text)
if m:
return m.group(1), where
m = re.search(rf"[\"']{re.escape(classpath)}:([^\"'$]+)[\"']", text)
if m:
return m.group(1), where
return None, None
def load_package(raw: str) -> dict[str, Any]:
"""pack.json of a package written by this script, plus its folder."""
folder = pathlib.Path(raw).expanduser().resolve()
try:
data = json.loads((folder / "pack.json").read_text(encoding="utf-8"))
except (OSError, ValueError) as e:
raise PackError(
2,
f"--package {folder}: no readable pack.json ({e}). Pass the folder "
"package_ai_pack.py wrote (the one with INTEGRATION.md).",
) from e
if not isinstance(data, dict) or data.get("generator") != GENERATOR:
raise PackError(
2, f"{folder / 'pack.json'} was not written by package_ai_pack.py.")
return dict(data, folder=folder)
def find_app_module(project: dict[str, Any], args: argparse.Namespace,
packaged: str) -> tuple[dict[str, Any], str | None]:
"""The app module (--app-module, else the package's, else the only one)."""
wanted = (args.app_module if "app_module" in args.explicit
else packaged).strip(":")
for module in project["modules"]:
if ((module["gradle_path"] or "").strip(":") == wanted
or module["rel"] == wanted.replace(":", "/")):
return module, None
apps = [m for m in project["modules"] if applies_app_plugin(m["text"])]
if len(apps) == 1 and "app_module" not in args.explicit:
name = apps[0]["gradle_path"] or apps[0]["rel"]
return apps[0], (f"the package was made for the app module :{wanted}; "
f"this project's app module is {name}")
names = ", ".join(m["gradle_path"] or m["rel"] for m in apps) or "none"
raise PackError(
2,
f"no app module :{wanted} in {project['root']} (app modules found: "
f"{names}). Pass --app-module.",
)
def check_integration(pkg: dict[str, Any], project: dict[str, Any],
args: argparse.Namespace,
pins: dict[str, Any]) -> dict[str, Any]:
"""Every requirement of the package's INTEGRATION.md, checked."""
root, folder = project["root"], pkg["folder"]
pack, model, delivery = pkg["pack_name"], pkg["model_name"], pkg["delivery"]
litert = pkg.get("litert") or {}
release = litert.get("maven_release") or pins.get("maven_release")
kotlin_need = litert.get("kotlin_min") or pins.get("kotlin_min") or "0"
socs = [v["soc"] for v in pkg["variants"]]
app, app_note = find_app_module(project, args,
pkg.get("app_module") or "app")
app_dir, app_rel, text = app["dir"], app["rel"], app["text"]
app_path = app["gradle_path"] or ":" + app_rel.replace("/", ":")
build_file = app["build_file"]
kts = build_file.endswith(".kts")
lang = "kotlin" if kts else "groovy"
q = '"' if kts else "'"
prefix = "" if app_rel == "." else app_rel + "/"
checks: list[dict[str, Any]] = []
def add(name: str, status: str, detail: str,
fix: dict[str, Any] | None = None, risky: bool = False) -> None:
checks.append({"check": name, "status": status, "detail": detail,
"fix": None if status == "pass" else fix,
"risky": risky and status == "fail"})
def copy_fix(source: str, target: str, what: str) -> dict[str, Any]:
src, dst = folder / source, root / target
parent = shlex.quote(str(dst.parent))
if src.is_dir():
command = (f"mkdir -p {parent} && cp -r {shlex.quote(str(src))} "
f"{parent}/")
else:
command = (f"mkdir -p {parent} && cp {shlex.quote(str(src))} "
f"{shlex.quote(str(dst))}")
return {"action": "copy", "file": target, "text": f"Copy {what}.",
"snippet": command, "lang": "bash", "from": source}
def edit_fix(file: str, what: str, snippet: str | None,
snippet_lang: str = lang) -> dict[str, Any]:
return {"action": "edit", "file": file, "text": what,
"snippet": snippet, "lang": snippet_lang, "from": None}
def same(a: pathlib.Path, b: pathlib.Path) -> bool:
return b.is_file() and _sha256(a) == _sha256(b)
# Files from the package: AI pack, runtime modules, XML, CPU model.
pack_rel = f"ai_packs/{pack}"
assets = sorted(p for p in (folder / pack_rel / "src").rglob("*")
if p.is_file())
missing = [p for p in assets if not (root / p.relative_to(folder)).is_file()]
differ = [p for p in assets if p not in missing
and not same(p, root / p.relative_to(folder))]
pack_build = next((root / pack_rel / n for n in BUILD_FILES
if (root / pack_rel / n).is_file()), None)
if pack_build is None or missing or differ:
detail = (f"{pack_rel}/ is missing" if not (root / pack_rel).exists()
else f"{pack_rel}/: {len(missing)} file(s) missing, "
f"{len(differ)} differ from the package")
add("AI pack module", "fail", detail,
copy_fix(pack_rel, pack_rel, f"the AI pack module {pack_rel}/"),
risky=bool(differ))
else:
pack_text = _strip_comments(_read_text(pack_build))
name = _PACK_NAME_RE.search(pack_text)
pack_delivery = _DELIVERY_RE.search(pack_text)
if (not name or name.group(1) != pack or not pack_delivery
or pack_delivery.group(1) != delivery):
add("AI pack module", "fail",
f"{_rel(pack_build, root)} does not set packName \"{pack}\" and "
f"deliveryType \"{delivery}\"",
copy_fix(f"{pack_rel}/build.gradle.kts",
f"{pack_rel}/build.gradle.kts",
"the package's AI pack build file"), risky=True)
else:
add("AI pack module", "pass",
f"{pack_rel}/: the models are byte-identical to the package")
for module_name, gradle_path in (("google_tensor_runtime",
RUNTIME_MODULE_PATH),
("runtime_strings", STRINGS_MODULE_PATH)):
rel = f"litert_npu_runtime_libraries/{module_name}"
if any((root / rel / n).is_file() for n in BUILD_FILES):
add(f"Module {gradle_path}", "pass", f"{rel}/ is there")
else:
add(f"Module {gradle_path}", "fail", f"{rel}/ is missing",
copy_fix(rel, rel, f"the {module_name} module"))
runtime_dir = root / "litert_npu_runtime_libraries" / "google_tensor_runtime"
runtime_build = next((runtime_dir / n for n in BUILD_FILES
if (runtime_dir / n).is_file()), None)
if runtime_build:
runtime_text = _strip_comments(_read_text(runtime_build))
problems = []
dep = re.search(rf"[\"']{re.escape(LITERT_MAVEN_GROUP)}:"
rf"{re.escape(RUNTIME_ARTIFACT)}:([^\"']+)[\"']",
runtime_text)
if dep and "$" not in dep.group(1) and dep.group(1) != release:
problems.append(f"it uses {RUNTIME_ARTIFACT} {dep.group(1)}, not "
f"{release}")
project_dep = _PROJECT_DEP_RE.search(runtime_text)
if project_dep and project_dep.group(1) != app_path:
problems.append(f"it depends on project(\"{project_dep.group(1)}\"), "
f"but the app module is {app_path}")
try:
manifest = ET.parse(runtime_dir / "src" / "main"
/ "AndroidManifest.xml").getroot()
module_groups = {g.get(f"{{{DIST_NS}}}name")
for g in manifest.iter(f"{{{DIST_NS}}}device-group")}
except (OSError, ET.ParseError):
module_groups = set()
lacking = [g for g in pkg["device_groups"] if g not in module_groups]
if lacking:
problems.append("its manifest does not deliver it to "
+ ", ".join(lacking))
if problems:
add("Runtime module content", "fail", "; ".join(problems),
edit_fix(_rel(runtime_build, root),
f"Depend on project(\"{app_path}\") and "
f"{LITERT_MAVEN_GROUP}:{RUNTIME_ARTIFACT}:{release}, and "
"list the pack's device groups in its manifest (copy the "
"package's module again if it was not changed on "
"purpose).",
f'implementation(project("{app_path}"))\n'
f'implementation("{LITERT_MAVEN_GROUP}:{RUNTIME_ARTIFACT}'
f':{release}")', "kotlin"))
else:
add("Runtime module content", "pass",
f"depends on {app_path} and {RUNTIME_ARTIFACT}, delivered to the "
"pack's groups")
dtc = next((d for d in find_dtcs(project) if d["module"] is app), None)
xml_path = (dtc["path"] if dtc
else app_dir / "device_targeting_configuration.xml")
xml_rel = _rel(xml_path, root)
package_xml = folder / "ai_packs" / "device_targeting_configuration.xml"
if not xml_path.is_file():
add("Device-targeting XML", "fail", f"{xml_rel} is missing",
copy_fix("ai_packs/device_targeting_configuration.xml", xml_rel,
"the device-targeting XML"))
else:
want, have = parse_dtc(package_xml), parse_dtc(xml_path)
lacking = [g for g in want if have.get(g) != want[g]]
if lacking:
package_text = package_xml.read_text(encoding="utf-8")
add("Device-targeting XML", "fail",
f"{xml_rel} does not define {', '.join(lacking)} as the package "
"does",
edit_fix(xml_rel, "Add (or replace) these elements inside "
"<config:device-targeting-config>, unchanged.",
"\n".join(_exported_group(package_text, g) or g
for g in lacking), "xml"))
else:
add("Device-targeting XML", "pass",
f"{xml_rel} defines " + ", ".join(want))
cpu = pkg["other_devices"]["cpu_model"]
cpu_rel = f"{prefix}src/main/assets/{cpu['app_asset']}"
if same(folder / cpu["packed_as"], root / cpu_rel):
add("CPU model", "pass", f"{cpu_rel} is the package's original model")
else:
add("CPU model", "fail",
f"{cpu_rel} is " + ("a different file" if (root / cpu_rel).is_file()
else "missing"),
copy_fix(cpu["packed_as"], cpu_rel, "the original (CPU) model"),
risky=(root / cpu_rel).is_file())
loader = find_loader(project, pack)
want_socs = sorted(soc_display(s) for s in socs)
package_dir = (pkg.get("kotlin_package") or "com.example.litert").replace(
".", "/")
if loader is None:
add("Model loader", "fail",
"no TensorModelLoader.kt for this pack in the app's sources",
copy_fix("kotlin/TensorModelLoader.kt",
f"{prefix}src/main/java/{package_dir}/TensorModelLoader.kt",
"TensorModelLoader.kt (its package line must match the "
"folder it goes into)"))
else:
wrong = []
if loader["model_path"] != f"model/{model}.tflite":
wrong.append(f"it opens {loader['model_path']}")
if loader["delivery"] != delivery:
wrong.append(f"its DELIVERY is {loader['delivery']}")
if loader["socs"] is not None and sorted(loader["socs"]) != want_socs:
wrong.append("its SoC list is " + ", ".join(loader["socs"]))
if wrong:
add("Model loader", "fail", f"{loader['file']}: " + "; ".join(wrong),
copy_fix("kotlin/TensorModelLoader.kt", loader["file"],
"the package's TensorModelLoader.kt over it (keep its "
"package line)"), risky=True)
else:
add("Model loader", "pass", f"{loader['file']} matches the package")
quick = pkg.get("quick_test")
if quick:
gaps = []
for entry in quick["files"]:
inside = pathlib.PurePosixPath(entry["packed_as"]).relative_to(
QUICK_TEST_DIR)
if not same(folder / entry["packed_as"],
app_dir / APP_QUICK_TEST_DIR / inside):
gaps.append(entry["soc"])
has_block = QUICK_TEST_PROPERTY in text
if gaps or not has_block:
add("Quick test (optional)", "warn",
("no build for " + ", ".join(gaps) + "; " if gaps else "")
+ ("the Gradle block is missing" if not has_block
else "the Gradle block is there"),
edit_fix(build_file,
f"Copy the package's {QUICK_TEST_DIR}/ to "
f"{prefix}{APP_QUICK_TEST_DIR}/ and add this block at the "
"end of the app's build file.",
QUICK_TEST_BLOCK[kts].format(release=release)))
else:
add("Quick test (optional)", "pass",
f"{prefix}{APP_QUICK_TEST_DIR}/ and the Gradle block are there")
# settings.gradle(.kts).
settings_rel = project["settings_rel"]
settings_kts = settings_rel.endswith(".kts")
need = [f":ai_packs:{pack}", STRINGS_MODULE_PATH, RUNTIME_MODULE_PATH]
lacking = [p for p in need if p not in project["gradle_paths"]]
if lacking:
add("Settings includes", "fail",
f"{settings_rel} does not include {', '.join(lacking)}",
edit_fix(settings_rel, "Add these lines.",
"\n".join(f'include("{p}")' if settings_kts
else f"include '{p}'" for p in lacking),
"kotlin" if settings_kts else "groovy"))
else:
add("Settings includes", "pass", "the pack and both runtime modules")
# The app module's build file.
def quoted(gradle_path: str) -> bool:
return bool(re.search(rf"[\"']{re.escape(gradle_path)}[\"']", text))
if "assetPacks" in text and quoted(f":ai_packs:{pack}"):
add("App: assetPacks", "pass", f":ai_packs:{pack} is listed")
else:
add("App: assetPacks", "fail", f"{build_file} does not list "
f":ai_packs:{pack} in assetPacks",
edit_fix(build_file, "Inside android { } (add it to the list if "
"assetPacks already names other packs):",
f'assetPacks.add(":ai_packs:{pack}")' if kts
else f"assetPacks = [':ai_packs:{pack}']"))
if "dynamicFeatures" in text and quoted(RUNTIME_MODULE_PATH):
add("App: dynamicFeatures", "pass", f"{RUNTIME_MODULE_PATH} is listed")
else:
add("App: dynamicFeatures", "fail", f"{build_file} does not list "
f"{RUNTIME_MODULE_PATH} in dynamicFeatures",
edit_fix(build_file, "Inside android { } (add it to the list if "
"dynamicFeatures already names other modules):",
f'dynamicFeatures.add("{RUNTIME_MODULE_PATH}")' if kts
else f"dynamicFeatures = ['{RUNTIME_MODULE_PATH}']"))
default_group = _DEFAULT_GROUP_RE.search(text)
bundle_issues = []
if dtc is None:
bundle_issues.append("no deviceTargetingConfig")
if not _ENABLE_SPLIT_RE.search(text):
bundle_issues.append("no deviceGroup enableSplit = true")
if not default_group or default_group.group(1) != "other":
bundle_issues.append("defaultGroup is not \"other\"")
if bundle_issues:
add("App: bundle device targeting", "fail", "; ".join(bundle_issues),
edit_fix(build_file, "Inside android { }:",
"bundle {\n"
f" deviceTargetingConfig = file({q}"
f"{_rel(xml_path, app_dir)}{q})\n"
" deviceGroup {\n"
" enableSplit = true\n"
f" defaultGroup = {q}other{q}\n"
" }\n"
"}"))
else:
add("App: bundle device targeting", "pass",
f"deviceTargetingConfig {xml_rel}, split by device group")
manifest_text = _read_text(app_dir / "src" / "main" / "AndroidManifest.xml")
if _LEGACY_PACKAGING_RE.search(text) or _EXTRACT_LIBS_RE.search(
manifest_text):
add("App: native libraries extracted", "pass",
"useLegacyPackaging = true")
else:
add("App: native libraries extracted", "fail",
"LiteRT finds the NPU runtime by listing the native library folder, "
"so the libraries must be extracted at install",
edit_fix(build_file, "Inside android { }:",
"packaging { jniLibs { useLegacyPackaging = true } }"))
min_sdk = _MIN_SDK_RE.search(text)
if not min_sdk:
add("App: minSdk", "warn", f"no minSdk in {build_file} (it may come from "
f"a convention plugin); it must be {MIN_SDK} or higher",
edit_fix(build_file, f"Make sure minSdk is {MIN_SDK} or higher.",
None))
elif int(min_sdk.group(1)) < MIN_SDK:
add("App: minSdk", "fail", f"minSdk is {min_sdk.group(1)}; LiteRT needs "
f"{MIN_SDK}: phones below Android 12 could no longer install the app",
edit_fix(build_file, "In defaultConfig:",
f"minSdk = {MIN_SDK}" if kts else f"minSdk {MIN_SDK}"),
risky=True)
else:
add("App: minSdk", "pass", f"minSdk {min_sdk.group(1)}")
abis = abi_filters(text)
abi_fix = edit_fix(build_file, "In defaultConfig:",
f'ndk {{ abiFilters.add("{RUNTIME_ABI}") }}' if kts
else f"ndk {{ abiFilters '{RUNTIME_ABI}' }}")
narrows = ("bundletool needs the same ABIs in every module, and the Google "
f"Tensor runtime has only {RUNTIME_ABI}; devices without "
f"{RUNTIME_ABI} could no longer install the app")
others = sorted((abis or set()) - {RUNTIME_ABI})
if abis == {RUNTIME_ABI}:
add("App: ABI filters", "pass", f"{RUNTIME_ABI} only")
elif abis is None:
add("App: ABI filters", "fail", "no abiFilters, so the app ships every "
f"ABI of its native libraries; {narrows}", abi_fix, risky=True)
elif others:
add("App: ABI filters", "fail",
f"abiFilters {'also ' if RUNTIME_ABI in abis else ''}names "
f"{', '.join(others)}; {narrows}",
dict(abi_fix, text=f"Make abiFilters {RUNTIME_ABI} only (remove "
f"{', '.join(others)}):"), risky=True)
else:
add("App: ABI filters", "warn", "abiFilters is set from a value the "
f"check cannot read; it must be {RUNTIME_ABI} only")
runtime = detect_runtime(project)
core = {r["version"] or "unknown" for r in runtime["core"]
if r["module"] == app_rel}
litert_dep = (f'implementation("{LITERT_MAVEN_GROUP}:litert:{release}")'
if kts else
f"implementation '{LITERT_MAVEN_GROUP}:litert:{release}'")
if core == {release}:
add("App: LiteRT dependency", "pass", f"litert {release}")
elif not core:
add("App: LiteRT dependency", "fail",
f"{build_file} does not depend on {LITERT_MAVEN_GROUP}:litert",
edit_fix(build_file, "In dependencies { }:", litert_dep))
elif core == {"unknown"}:
add("App: LiteRT dependency", "warn", "the litert version could not be "
f"read; it must be {release}, the release of the runtime module")
else:
add("App: LiteRT dependency", "fail",
f"the app uses litert {', '.join(sorted(core))}; the runtime module "
f"needs {release} (one release for both)",
edit_fix(build_file, "In dependencies { }:", litert_dep), risky=True)
if re.search(rf"project\(\s*(?:path\s*[:=]\s*)?[\"']"
rf"{re.escape(STRINGS_MODULE_PATH)}[\"']", text):
add("App: runtime_strings dependency", "pass", STRINGS_MODULE_PATH)
else:
add("App: runtime_strings dependency", "fail",
f"{build_file} does not depend on {STRINGS_MODULE_PATH}",
edit_fix(build_file, "In dependencies { }:",
f'implementation(project("{STRINGS_MODULE_PATH}"))' if kts
else f"implementation project('{STRINGS_MODULE_PATH}')"))
# gradle.properties, manifest permissions, plugin versions.
if re.search(rf"(?m)^\s*{re.escape(DEVICE_TARGETING_FLAG)}\s*=\s*true\s*$",
project["properties"]):
add("gradle.properties", "pass", f"{DEVICE_TARGETING_FLAG}=true")
else:
add("gradle.properties", "fail", f"{DEVICE_TARGETING_FLAG}=true is "
"missing (device targeting is ignored without it)",
edit_fix("gradle.properties", "Add this line.",
f"{DEVICE_TARGETING_FLAG}=true", "properties"))
if delivery != "install-time":
lacking = [p for p in DOWNLOAD_PERMISSIONS if p not in manifest_text]
if lacking:
add("App: download permissions", "fail",
f"{delivery} packs need " + ", ".join(lacking),
edit_fix(f"{prefix}src/main/AndroidManifest.xml",
"Inside <manifest>:", "\n".join(
f'<uses-permission android:name="{p}" />'
for p in lacking), "xml"))
else:
add("App: download permissions", "pass", "FOREGROUND_SERVICE(_DATA_"
"SYNC) declared")
agp, agp_where = plugin_version(project, AGP_PLUGIN_IDS, AGP_CLASSPATH)
if agp is None:
add("Android Gradle plugin", "warn", "version not found; it must be "
f"{'.'.join(map(str, MIN_AGP))} or newer for device targeting")
elif _version_tuple(agp) < MIN_AGP:
add("Android Gradle plugin", "fail",
f"{agp} ({agp_where}); device targeting needs "
f"{'.'.join(map(str, MIN_AGP))} or newer. Upgrading affects the "
"whole build",
edit_fix(agp_where, "Raise the Android Gradle plugin version to "
f"{'.'.join(map(str, MIN_AGP))} or newer (and Gradle to "
"what it requires).", None), risky=True)
else:
add("Android Gradle plugin", "pass", f"{agp} ({agp_where})")
kotlin, kotlin_where = plugin_version(project, KOTLIN_PLUGIN_IDS,
KOTLIN_CLASSPATH)
if kotlin is None and not _KOTLIN_APPLIED_RE.search(text):
built_in = agp is not None and _version_tuple(agp) >= (9,)
add("Kotlin", "warn" if built_in else "fail",
"the app module applies no Kotlin plugin, but TensorModelLoader.kt "
"is Kotlin" + (" (AGP 9 may build it without one)" if built_in
else ""),
edit_fix(build_file, "Apply the Kotlin Android plugin "
f"(org.jetbrains.kotlin.android) {kotlin_need} or newer.",
None), risky=not built_in)
elif kotlin is None:
add("Kotlin", "warn", f"version not found; it must be {kotlin_need} or "
f"newer to read LiteRT {release}'s Kotlin API")
elif _version_tuple(kotlin) < _version_tuple(kotlin_need):
add("Kotlin", "fail", f"{kotlin} ({kotlin_where}); LiteRT {release}'s "
f"Kotlin API needs {kotlin_need} or newer",
edit_fix(kotlin_where, f"Raise the Kotlin version to {kotlin_need} "
"or newer.", None), risky=True)
else:
add("Kotlin", "pass", f"{kotlin} ({kotlin_where})")
fails = [c for c in checks if c["status"] == "fail"]
return {
"project": str(root),
"package": str(folder),
"pack": pack,
"delivery": delivery,
"socs": socs,
"app_module": {"module": app_rel, "gradle_path": app_path,
"build_file": build_file},
"notes": [app_note] if app_note else [],
"checks": checks,
"summary": {
"to_do": len(fails),
"risky": [c["check"] for c in fails if c["risky"]],
"warnings": sum(c["status"] == "warn" for c in checks),
"passed": sum(c["status"] == "pass" for c in checks),
},
}
def print_check_report(result: dict[str, Any]) -> None:
"""Prints the --check-project report: each check, its fix and a summary."""
app = result["app_module"]
print(f"**Integration check:** {result['project']} for the package "
f"{result['package']} (pack `{result['pack']}`, "
f"`{result['delivery']}`, {_socs_text(result['socs'])})")
print(f"**App module:** `{app['gradle_path']}` (`{app['build_file']}`)")
for c in result["checks"]:
print(f" {c['status'].upper():<5} {c['check']}: {c['detail']}")
fix = c["fix"]
if fix:
where = f" ({fix['file']})" if fix.get("file") else ""
risky = " [needs a separate OK]" if c["risky"] else ""
print(f" fix{where}{risky}: {fix['text']}")
for line in (fix.get("snippet") or "").splitlines():
print(f" {line}")
s = result["summary"]
risky = (f" ({len(s['risky'])} need a separate OK: "
f"{', '.join(s['risky'])})" if s["risky"] else "")
print(f"**Result:** {s['to_do']} to do{risky}, {s['warnings']} "
f"warning(s), {s['passed']} passed")
for note in result["notes"]:
print(f"NOTE: {note}")
def main_check(args: argparse.Namespace, versions: dict[str, Any],
versions_error: str | None) -> int:
"""--check-project (read-only): is the project set up for the package?"""
del versions_error # Unused.
if args.compiled or args.fallback or args.update_project:
raise PackError(
2, "--check-project takes --package (the folder package_ai_pack.py "
"wrote), not --compiled, --fallback or --update-project.")
if not args.package:
raise PackError(2, "--check-project needs --package <the folder "
"package_ai_pack.py wrote>.")
pins = {"maven_release": versions.get("maven_release"),
"kotlin_min": versions.get("kotlin_min")}
pkg = load_package(args.package)
project = inspect_project(args.check_project)
result = check_integration(pkg, project, args, pins)
if args.json:
print(json.dumps(result, indent=2))
else:
print_check_report(result)
return 1 if result["summary"]["to_do"] else 0
# --------------------------------------------------------------------------
# Main
# --------------------------------------------------------------------------
def build_package(args: argparse.Namespace, builds: dict[str, dict[str, Any]],
fallback: dict[str, Any], out: pathlib.Path, release: str,
min_kotlin: str, versions: dict[str, Any],
notes: list[str]) -> dict[str, Any]:
"""Writes the package into a staging directory, verifies it, moves it."""
stage = out.parent / f".{out.name}.staging-{os.getpid()}"
if stage.exists():
shutil.rmtree(stage)
stage.mkdir(parents=True)
try:
ai_packs = stage / "ai_packs"
export_with_litert(builds, fallback, ai_packs, args.pack_name,
args.model_name, versions.get("pip_release"))
# D1: devices outside the Google Tensor groups use the base-asset CPU
# model, so the exporter's copy of the original becomes a placeholder.
other = (ai_packs / args.pack_name / "src" / "main" / "assets"
/ OTHER_GROUP_DIR)
for path in other.iterdir():
path.unlink()
(other / PLACEHOLDER_FILE).write_text(
PLACEHOLDER_TEXT.format(model=args.model_name, generator=GENERATOR),
encoding="utf-8",
)
cpu_dir = stage / "cpu_gpu"
cpu_dir.mkdir()
shutil.copyfile(fallback["path"],
cpu_dir / f"{args.model_name}_cpu_gpu.tflite")
# Optional quick test: each Tensor build where a debug APK's assets can
# carry it (INTEGRATION.md, "Optional: quick test without bundletool").
quick_test = None
if args.quick_test:
quick_test = {"app_dir": APP_QUICK_TEST_DIR,
"gradle_property": QUICK_TEST_PROPERTY, "files": []}
for soc in builds:
source = (ai_packs / args.pack_name / "src" / "main" / "assets"
/ f"model#group_{group_of(soc)}"
/ f"{args.model_name}.tflite")
rel = quick_test_file(soc, args.model_name)
(stage / rel).parent.mkdir(parents=True)
shutil.copyfile(source, stage / rel)
quick_test["files"].append({"soc": soc, "packed_as": rel})
values = template_values(args, builds, release, min_kotlin)
if quick_test:
values["QUICK_TEST_SECTION"] = render("INTEGRATION_quick_test.md",
values)
for template, target in TEMPLATE_OUTPUTS:
dest = stage / target.format(pack=args.pack_name)
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(render(template, values), encoding="utf-8")
io_error = write_model_io(fallback["path"], stage)
if io_error:
notes.append(f"model_io.json: could not read the signature ({io_error}).")
checks = verify_package(stage, args, builds, fallback)
summary = {
"generator": GENERATOR,
"generated_at": datetime.datetime.now(datetime.timezone.utc)
.strftime("%Y-%m-%dT%H:%M:%SZ"),
"pack_name": args.pack_name,
"model_name": args.model_name,
"delivery": args.delivery,
"app_module": args.app_module,
"kotlin_package": args.kotlin_package,
"device_groups": [group_of(s) for s in builds],
"variants": [
{
"device_group": group_of(soc),
"soc": soc,
"source": str(info["path"]),
"size_bytes": info["size_bytes"],
"sha256": info["sha256"],
"packed_as": (f"ai_packs/{args.pack_name}/src/main/assets/"
f"model#group_{group_of(soc)}/"
f"{args.model_name}.tflite"),
"sidecar": _sidecar_summary(info.get("sidecar")),
}
for soc, info in builds.items()
],
"other_devices": {
"ai_pack_folder": (f"ai_packs/{args.pack_name}/src/main/assets/"
f"{OTHER_GROUP_DIR}/{PLACEHOLDER_FILE}"),
"cpu_model": {
"source": str(fallback["path"]),
"size_bytes": fallback["size_bytes"],
"sha256": fallback["sha256"],
"packed_as": f"cpu_gpu/{args.model_name}_cpu_gpu.tflite",
"app_asset": f"litert/{args.model_name}_cpu_gpu.tflite",
},
},
"quick_test": quick_test,
"litert": {
"maven_release": release,
"kotlin_min": min_kotlin,
"maven_artifacts": [
f"com.google.ai.edge.litert:litert:{release}",
"com.google.ai.edge.litert:litert-npu-runtime-google-tensor:"
f"{release}",
],
"exporter": "ai_edge_litert.aot.ai_pack.export_lib",
"exporter_package": installed_litert(),
"pinned_pip_release": versions.get("pip_release"),
},
"checks": checks,
"notes": notes,
}
(stage / "pack.json").write_text(
json.dumps(summary, indent=2) + "\n", encoding="utf-8"
)
values["GENERATED_AT"] = summary["generated_at"].replace("T", " ")
values["TREE"] = tree_text(stage)
(stage / "INTEGRATION.md").write_text(
render("INTEGRATION.md", values), encoding="utf-8"
)
if out.exists():
shutil.rmtree(out)
out.parent.mkdir(parents=True, exist_ok=True)
os.replace(stage, out)
return summary
finally:
if stage.exists():
shutil.rmtree(stage, ignore_errors=True)
def _sidecar_summary(sidecar: dict[str, Any] | None) -> dict[str, Any] | None:
if not sidecar:
return None
keys = ("cli_flags", "ops_offloaded", "ops_total", "fully_compiled",
"packages", "compiled_at", "compiled_via")
return {k: sidecar[k] for k in keys if k in sidecar}
def report_markdown(summary: dict[str, Any], out: pathlib.Path) -> str:
"""The Markdown summary printed after a package is written."""
files = [p for p in out.rglob("*") if p.is_file()]
total = sum(p.stat().st_size for p in files)
lines = [
f"**Packaged:** {out} ({len(files)} files, {fmt_size(total)})",
f"**AI pack:** `{summary['pack_name']}` (`{summary['delivery']}` "
f"delivery); the app opens `model/{summary['model_name']}.tflite`",
]
for v in summary["variants"]:
sidecar = v["sidecar"]
if sidecar:
ops = (f"{sidecar.get('ops_offloaded')} / {sidecar.get('ops_total')} "
"ops offloaded")
origin = f"SHA-256 matches its .compile.json; {ops}"
else:
origin = "no .compile.json: flags unknown"
lines.append(f"**{v['device_group']}:** {pathlib.Path(v['source']).name} "
f"({origin})")
cpu = summary["other_devices"]["cpu_model"]
lines += [
f"**Other devices:** placeholder in `{OTHER_GROUP_DIR}`; CPU model "
f"`{cpu['packed_as']}` -> app assets `{cpu['app_asset']}`",
]
if summary.get("quick_test"):
lines.append(
f"**Quick test:** `{QUICK_TEST_DIR}/` -> `<app module>/"
f"{APP_QUICK_TEST_DIR}/`, for `./gradlew installDebug "
f"-P{QUICK_TEST_PROPERTY}=<SoC>` (local testing only; INTEGRATION.md, "
"\"Optional: quick test without bundletool\")")
lines += [
"**LiteRT (Maven):** " + " + ".join(
f"`{a}`" for a in summary["litert"]["maven_artifacts"]),
f"**Exporter:** {summary['litert']['exporter']} "
f"({summary['litert']['exporter_package']})",
f"**Verified:** {len(summary['checks'])} checks passed (pack.json "
"lists them)",
f"**Next:** {out / 'INTEGRATION.md'}",
]
return "\n".join(lines)
def print_plan(args: argparse.Namespace, builds: dict[str, dict[str, Any]],
fallback: dict[str, Any], out: pathlib.Path, release: str,
min_kotlin: str, notes: list[str]) -> None:
"""Prints the dry-run plan of a new package (nothing is written)."""
print("Dry run: inputs checked; nothing imported or written.")
for soc, info in builds.items():
sidecar = "sidecar OK" if info.get("sidecar") else "no sidecar"
print(f" {group_of(soc)} <- {info['path']} "
f"({fmt_size(info['size_bytes'])}, {sidecar})")
print(f" CPU model <- {fallback['path']} "
f"({fmt_size(fallback['size_bytes'])})")
print(f"Pack: {args.pack_name} ({args.delivery}); model file "
f"model/{args.model_name}.tflite; app module :{args.app_module}")
print(f"LiteRT Maven release for the Gradle files: {release} (apps need "
f"Kotlin {min_kotlin} or newer)")
if args.quick_test:
print(f"Quick test: {QUICK_TEST_DIR}/<SoC>/assets/ for "
f"./gradlew installDebug -P{QUICK_TEST_PROPERTY}=<SoC> (local "
"testing only)")
print(f"Would write: {out}{' (replacing it)' if out.exists() else ''}")
for note in notes:
print(f"NOTE: {note}")
def main(argv=None) -> int:
args = parse_args(argv)
versions, versions_error = read_versions()
try:
if args.check_project:
return main_check(args, versions, versions_error)
if args.package:
raise PackError(2, "--package needs --check-project.")
if not args.compiled or not args.fallback:
raise PackError(
2, "--compiled and --fallback are required (or --check-project "
"with --package to check a project).")
if args.update_project:
return main_update(args, versions, versions_error)
if args.cpu_asset:
raise PackError(2, "--cpu-asset needs --update-project.")
fallback_path = pathlib.Path(args.fallback).expanduser()
check_names(args, fallback_path)
builds, fallback, notes = check_inputs(args)
out = resolve_output_dir(args, fallback)
if args.dry_run:
try:
release = maven_release(versions, versions_error)
min_kotlin = kotlin_min(versions, versions_error)
except PackError as e:
release = min_kotlin = f"<unavailable: {e}>"
if args.json:
print(json.dumps({
"dry_run": True, "output_dir": str(out),
"pack_name": args.pack_name, "model_name": args.model_name,
"delivery": args.delivery,
"device_groups": [group_of(s) for s in builds],
"maven_release": release, "kotlin_min": min_kotlin,
"quick_test": args.quick_test,
"notes": notes,
}, indent=2))
else:
print_plan(args, builds, fallback, out, release, min_kotlin, notes)
return 0
release = maven_release(versions, versions_error)
min_kotlin = kotlin_min(versions, versions_error)
if not args.json:
print(f"Packaging {', '.join(group_of(s) for s in builds)} for AI pack "
f"'{args.pack_name}' with LiteRT's export_lib ...", flush=True)
summary = build_package(args, builds, fallback, out, release, min_kotlin,
versions, notes)
except PackError as e:
if args.json:
print(json.dumps({"status": "error", "exit_code": e.code,
"error": str(e)}, indent=2))
else:
print(f"ERROR: {e}", file=sys.stderr)
return e.code
except KeyboardInterrupt:
print("Interrupted; nothing was left at the output directory.",
file=sys.stderr)
return 130
if args.json:
print(json.dumps(dict(status="ok", output_dir=str(out), **summary),
indent=2))
else:
for note in summary["notes"]:
print(f"NOTE: {note}")
print()
print(report_markdown(summary, out))
return 0
if __name__ == "__main__":
sys.exit(main())
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE