TL;DR Many mobile AI tasks (image watermark removal, OCR assist, offline translation, text classification) don't need a constant connection at all: once they run locally, latency drops from ~800ms in the cloud to ~30ms on-device, and the privacy boundary gets much clearer. TFLite's strength isn't being "state of the art" — it's being engineered enough: model size, inference speed, device compatibility, and dual-platform integration paths are all out in the open. The real traps are pre- and post-processing: size normalization, color channels, quantization precision, output interpretation — get one wrong and the results are completely distorted. Four optimization rules: load the model exactly once, enable delegates whenever possible, reuse ByteBuffers in pre/post-processing to avoid bitmap copies, and push inference to a background thread. But don't go local for local's sake: if the model is too big, accuracy demands are extreme, or you need constant hot updates — just use the cloud. The approach should be driven by the scenario, not by ideology.

It started with something very concrete: last year on a high-speed train going through a tunnel, signal flickering in and out, I wanted to look up how to say “红烧狮子头” (braised pork meatballs) in English — and the offline translation pack saved me. That’s when it hit me: “works without network” isn’t a nice-to-have. For a lot of scenarios, it’s the whole game.

So I spent two weeks moving two tasks onto the phone — image watermark removal and offline translation — running them with TFLite. This post is the engineering notebook from those two weeks: picking models, quantization, delegate acceleration, and the pre/post-processing traps that made me question my life choices.

Editorial collage of on-device AI inference: phone chip cross-section, neural network, watermark removal and offline translation
Opening collage of on-device AI: a phone cross-section revealing its on-device chip, surrounded by a neural-network node diagram, a photo having its watermark erased, and Chinese–English offline translation bubbles — all inference happens on the device.

The Problem

Let’s do the math first. Cloud AI latency looks like this: network RTT 300–800ms + server inference 200–500ms + queue jitter — one request easily breaks a second, and it flat-out refuses to work with no signal. On-device latency looks like this: preprocessing 5–12ms + inference 18–55ms + postprocessing 3–8ms, end-to-end under 120ms, happily running inside a subway tunnel.

But going local has three gates, and each one has to be walked through honestly:

Gate one: model size. Nobody will download an extra 200MB for a translation feature. int8 quantization is the standard answer: FP32 → int8 cuts the size to a quarter, with accuracy typically dropping only 1–2 points. A quantized MobileNetV1 (224 input) is ~4.3MB; an offline translation model ~30MB — that’s the size class that belongs in an install package.

Gate two: inference speed. Pure CPU on 224×224 classification is ~55ms (4 threads) — usable, not silky. Delegates are the accelerators: NNAPI talks to the system’s neural-network interface, the GPU delegate rides OpenGL/Vulkan, and on my mid-range test phone they squeezed inference to ~18ms — 2–3x faster. Delegates fall back to CPU automatically on failure, so “enable when possible, shrug when not” is a safe policy.

Gate three: pre/post-processing. This is TFLite’s true trap king. Whatever normalization the model used in training (say mean=127.5, std=127.5) must be reproduced character-for-character at inference; quantized models eat uint8 (0–255) — apply float-model normalization to one and the output is silently, completely wrong. Mix up RGB and BGR channels and the classifier can confidently call a cat a truck.

The Approach

My inference pipeline: input → preprocessing (resize + normalize) → quantized model → delegate acceleration → postprocessing (decode output). Every step has its opinions.

Load the model exactly once with a memory-mapped file to avoid repeat IO, and try delegates by priority:

val options = Interpreter.Options().apply {
    setNumThreads(4)
    // NNAPI first, automatic CPU fallback on failure; older phones can use the GPU delegate
    try { addDelegate(NnApiDelegate()) } catch (e: Exception) { /* fallback to CPU */ }
}

val modelBuffer: MappedByteBuffer = FileUtil.loadMappedFile(context, "mobilenet_v1_1.0_224_quant.tflite")
val interpreter = Interpreter(modelBuffer, options) // hold as a singleton, never new() per call

The key to preprocessing is “exactly like training.” A quantized model takes uint8 — fill the bytes with raw 0–255 pixel values, no float normalization:

// Quantized model: fill pixel values into the ByteBuffer as-is, no mean/std normalization
val inputBuffer = ByteBuffer.allocateDirect(1 * 224 * 224 * 3).apply {
    order(ByteOrder.nativeOrder())
}
for (pixel in scaledBitmapPixels) {
    inputBuffer.put((pixel shr 16 and 0xFF).toByte()) // R
    inputBuffer.put((pixel shr 8 and 0xFF).toByte())  // G
    inputBuffer.put((pixel and 0xFF).toByte())        // B
}
Four iron rules of optimization
  • Load the model once: Interpreter init costs hundreds of milliseconds — singleton it and warm up at app start
  • Enable delegates whenever possible: NNAPI / GPU delegate first, automatic CPU fallback — never hardcode
  • Minimize bitmap copies: reuse the same ByteBuffer in preprocessing instead of allocateDirect on every inference
  • Inference goes to a background thread: coroutines on Dispatchers.Default; the UI only consumes state — 60fps is sacred

The inference call itself is plain; the thread is the point:

suspend fun classify(bitmap: Bitmap): List<Label> = withContext(Dispatchers.Default) {
    val input = preprocess(bitmap)   // the reused ByteBuffer
    val output = Array(1) { FloatArray(1001) }
    interpreter.run(input, output)   // 18–55ms depending on delegate
    postprocess(output[0])           // take top-k, map through the label file
}
The value of local AI isn't saving one request — it's the product still standing when there's no network.
Infographic of the TFLite on-device inference pipeline from camera input to quantized model and hardware acceleration
TFLite on-device inference pipeline infographic: camera input passes through resize and normalization into an int8-quantized model, NNAPI/GPU/CPU hardware acceleration picks the best available, and the output card shows detection boxes and translated text — each stage annotated with latency and memory orders of magnitude.

The Result

Measured on a mid-range phone (treat these as orders of magnitude from my test setup — your chip will vary):

  • Image classification (MobileNetV1 int8, 4.3MB): ~55ms on 4 CPU threads, ~18ms with the NNAPI delegate, end-to-end (with pre/post) under 120ms
  • Offline translation (~30MB model): 400ms first-load (one-time), then 20–40ms per sentence — perfectly usable in the subway
  • Watermark removal: small inpainting-style model ~200ms per 512×512 input — decent, but don’t expect Photoshop-grade
  • APK size delta: +4.3MB (classification) or +30MB (translation), both acceptable; the .so is ~1MB

The most visceral difference: “snap to translate” used to mean open, watch the spinner, watch it time out. Now you open it and the answer is already there. That “offline but actually good” feeling is something cloud solutions just can’t give you.

The State of Things

Google has renamed TFLite to LiteRT — the API migration is nearly seamless, so existing projects shouldn’t panic. On-device large models are the obvious trend: Gemini Nano-class on-device LLMs are entering phones, but a 3B-parameter model’s size and memory footprint are still far from “ship it inside a utility app.”

My take is layered: for discriminative small tasks — classification, detection, translation, OCR — TFLite/LiteRT is the best answer right now; for generative workloads, constant hot updates, or extreme accuracy sensitivity, use the cloud honestly. Don’t make the experience fragile just to serve a “purely local” ideology.

Hands-On Tonight

  1. Download mobilenet_v1_1.0_224_quant.tflite (~4.3MB) plus the labels file from the TensorFlow model zoo, drop them into app/src/main/assets
  2. Add org.tensorflow:tensorflow-lite + tensorflow-lite-support, write the singleton Interpreter from the snippet above, and get one image classified on CPU first
  3. Enable the NNAPI delegate, compare CPU vs. delegate inference time (timestamp with SystemClock.elapsedRealtime()), and watch the 2–3x speedup with your own eyes
  4. Deliberately get the normalization wrong once (e.g. float normalization on a quantized model) and watch the output go completely wrong — stepping into this pit yourself teaches it ten times better than reading about it
  5. Wrap inference in withContext(Dispatchers.Default) and confirm in Android Studio's Profiler that the main thread's frame rate is untouched

FAQ

Which scenarios fit local models?

Image watermark removal, OCR assist, offline translation, text classification. Once they run on-device, latency drops from seconds to milliseconds, the privacy boundary gets clearer, and the product still stands with no network.

Why TFLite?

Not because it’s the most advanced — because it’s engineered enough: model size, inference speed, device compatibility, and Android/iOS integration paths are all out in the open. It’s now called LiteRT, with a nearly seamless API migration.

What’s the biggest pitfall with TFLite?

Pre- and post-processing: normalization must match training character-for-character, quantized models eat uint8 so don’t apply float normalization, and don’t mix up RGB/BGR. Get one wrong and results are completely distorted — silently, with no error. The silent part is what stings.

What are the key performance optimizations for on-device inference?

Four rules: load the model once (singleton + warmup); enable delegates when possible (NNAPI/GPU, CPU fallback); reuse the ByteBuffer in preprocessing, minimize bitmap copies; run inference on a background thread and let the UI only consume state.

When should I not use local models?

When the model is too big for the APK, accuracy demands are extreme (not a single point to spare), or you need constant hot updates (ship today, replace tomorrow). Good approaches are scenario-driven, not ideology-driven.

How much accuracy does quantization cost?

int8 quantization typically cuts size to a quarter and costs 1–2 points of accuracy. Totally fine for classification and translation; for accuracy-critical tasks, do quantization-aware training first.

The X-thread version

1/ On a train through a tunnel with flickering signal, I needed to know how to say “红烧狮子头” in English — the offline translation pack saved me. That’s when I decided to move AI onto the phone: latency from 1s down to 30ms, works with zero bars 🧵 2/ The math: one cloud request = 300–800ms network RTT + 200–500ms inference, easily over a second and dead without signal. On-device = 10ms preprocessing + 30ms inference + 5ms postprocessing, end-to-end under 120ms. 3/ Gate one: model size. int8 quantization cuts FP32 to a quarter, costing only 1–2 accuracy points. Quantized MobileNetV1 is 4.3MB, offline translation ~30MB — the size class that belongs in an install package. 4/ Gate two: speed. Pure CPU ~55ms; NNAPI/GPU delegates squeeze it to ~18ms, 2–3x faster. Delegates fall back to CPU automatically, so the policy is “enable when possible, shrug when not.” 5/ Gate three: pre/post-processing, TFLite’s true trap king. Normalization must match training character-for-character; feed float normalization to a uint8 quantized model and the output is silently, completely wrong — with no error. That silence stings. 6/ Four iron rules: load the model once (singleton + startup warmup); delegates first; reuse one ByteBuffer in preprocessing; inference on Dispatchers.Default, UI only consumes state. 7/ Measured: classification end-to-end under 120ms; translation 20–40ms per sentence after a 400ms first load; watermark removal ~200ms per 512px image. APK grows just 4–30MB. 8/ Hands-on tonight: ① drop the mobilenet quant model in assets ② singleton Interpreter, classify on CPU ③ enable NNAPI and witness the 2–3x speedup ④ deliberately break normalization to see how it fails ⑤ Profiler-check the main thread stays at 60fps. 9/ The rule: discriminative small tasks (classification/detection/translation/OCR) are best local; generative, hot-update-hungry, accuracy-critical workloads go to the cloud. Scenario-driven, never ideology-driven. Full post: https://citygenius-blog.pages.dev/article/local-ai-tflite

一句话总结 很多移动端 AI 场景(图片去水印、OCR 辅助、离线翻译、文本分类)根本不需要永远联网:本地跑通之后,延迟从云端的 800ms 级掉到 30ms 级,隐私边界也更清晰。TFLite 的优点不是"最先进",而是足够工程化——模型体积、推理速度、设备兼容性、双端集成路径都摆在台面上。真正的坑在前后处理:尺寸归一化、颜色通道、量化精度、输出解释,一错结果全失真。优化记住四条:模型只加载一次、delegate 能开就开、前后处理复用 ByteBuffer 少做 bitmap 拷贝、推理扔后台线程。但也别为了本地而本地:模型太大、精度要求极高、要持续热更新,就老实上云——方案应该场景驱动,而不是理念驱动。

事情的起因很具体:去年坐高铁穿隧道,信号时有时无,我想查菜单上”红烧狮子头”用英文怎么说——离线翻译包救了我。那一刻我突然意识到,“没网也能用”不是锦上添花,是很多场景的生死线。

于是我花了两周,把图片去水印和离线翻译两个任务搬到了手机本地,用 TFLite 跑通。这篇文章是那两周的工程笔记:选模型、量化、delegate 加速、以及那些让我怀疑人生的前后处理坑。

手机端侧 AI 推理的杂志拼贴插图:芯片剖面、神经网络、去水印与离线翻译元素
端侧 AI 的开篇拼贴:手机剖面露出端侧芯片,周围是神经网络节点图、正在被擦除水印的照片,以及中英离线翻译气泡——全部推理都在设备本地完成。

问题

先算一笔账。云端 AI 的延迟长这样:网络 RTT 300–800ms + 服务端推理 200–500ms + 排队抖动,一次请求轻松破 1 秒,还要在没网时直接罢工。本地推理的延迟长这样:前处理 5–12ms + 推理 18–55ms + 后处理 3–8ms,端到端 120ms 以内,地铁隧道里照样跑。

但本地化有三道门槛,每一道都得老实迈过去:

第一道:模型体积。 用户不会为了一个翻译功能多下 200MB。int8 量化是标准答案:FP32 转 int8,体积直接砍到 1/4,精度通常只掉 1–2 个点。一个量化后的 MobileNetV1(224 输入)约 4.3MB,离线翻译模型约 30MB——这个量级才配进安装包。

第二道:推理速度。 纯 CPU 跑 224×224 分类约 55ms(4 线程),能用但不够丝滑。delegate 是加速器:NNAPI 走系统神经网络接口,GPU delegate 走 OpenGL/Vulkan,在我测试的中端机上能把推理压到 18ms 左右,快 2–3 倍。delegate 加载失败会自动回退 CPU,所以”能开就开,开不了拉倒”是安全策略。

第三道:前后处理。 这是 TFLite 真正的坑王。模型训练时用的归一化参数(比如 mean=127.5、std=127.5),推理时必须一字不差地复现;量化模型吃的是 uint8(0–255),你要是把 float 模型的归一化套上去,输出直接全错。颜色通道 RGB 和 BGR 搞反,分类结果能离谱到把猫认成卡车。

做法

我的推理管线长这样:输入 → 前处理(resize + 归一化)→ 量化模型 → delegate 加速 → 后处理(解码输出)。每一步都有讲究。

模型只加载一次,用内存映射避免重复 IO,delegate 按优先级尝试:

val options = Interpreter.Options().apply {
    setNumThreads(4)
    // NNAPI 优先,失败自动回退 CPU;老机型可换 GPU delegate
    try { addDelegate(NnApiDelegate()) } catch (e: Exception) { /* fallback to CPU */ }
}

val modelBuffer: MappedByteBuffer = FileUtil.loadMappedFile(context, "mobilenet_v1_1.0_224_quant.tflite")
val interpreter = Interpreter(modelBuffer, options) // 单例持有,别每次 new

前处理的关键是”和训练时完全一致”。量化模型的输入是 uint8,直接填 0–255 的字节,别做 float 归一化:

// 量化模型:像素值原样填入 ByteBuffer,不做 mean/std 归一化
val inputBuffer = ByteBuffer.allocateDirect(1 * 224 * 224 * 3).apply {
    order(ByteOrder.nativeOrder()
}
for (pixel in scaledBitmapPixels) {
    inputBuffer.put((pixel shr 16 and 0xFF).toByte()) // R
    inputBuffer.put((pixel shr 8 and 0xFF).toByte())  // G
    inputBuffer.put((pixel and 0xFF).toByte())        // B
}
四条优化铁律
  • 模型只加载一次:Interpreter 初始化要几百毫秒,做成单例,应用启动时预热
  • delegate 能开就开:NNAPI / GPU delegate 优先,失败自动回退 CPU,不写死
  • 少做 bitmap 拷贝:前处理复用同一块 ByteBuffer,别每次推理都 allocateDirect
  • 推理扔后台线程:协程 Dispatchers.Default 跑推理,UI 只消费状态,60fps 不能掉

推理调用本身很朴素,重点是线程:

suspend fun classify(bitmap: Bitmap): List<Label> = withContext(Dispatchers.Default) {
    val input = preprocess(bitmap)   // 复用的 ByteBuffer
    val output = Array(1) { FloatArray(1001) }
    interpreter.run(input, output)   // 18–55ms,取决于 delegate
    postprocess(output[0])           // 取 top-k,映射 label 文件
}
本地 AI 的价值不只是省一次请求,而是让产品在"没有网络的时候"依然成立。
TFLite 端侧推理管线的信息图:从相机输入到量化模型与硬件加速再到输出
TFLite 端侧推理管线信息图:相机输入经缩放与归一化进入 int8 量化模型,NNAPI/GPU/CPU 三档硬件加速择优执行,最终输出检测框与翻译文本,各阶段标注了延迟与内存占用量级。

结果

中端机实测(以下数字是我的测试环境量级,不同芯片会有浮动):

  • 图像分类(MobileNetV1 int8,4.3MB):CPU 4 线程约 55ms,NNAPI delegate 约 18ms,端到端(含前后处理)120ms 以内
  • 离线翻译(约 30MB 模型):首包加载 400ms(一次性),之后每句 20–40ms,地铁里随便用
  • 图片去水印:inpainting 类小模型单次约 200ms,512×512 输入,效果能打但别指望 PS 级
  • APK 体积增量:+4.3MB(分类)或 +30MB(翻译),都在可接受范围;so 库约 1MB

最直观的对比:以前”拍照翻译”要点开、等转圈、看超时;现在点开就是结果。那种”离线但好用”的踏实感,是云端方案给不了的。

现状

Google 已经把 TFLite 改名为 LiteRT,API 几乎无缝迁移,老项目不用慌。端侧大模型是明显趋势:Gemini Nano 这类端侧 LLM 开始进手机,但 3B 参数的模型体积和内存占用,离”塞进工具类 App”还有距离。

我的判断是分层:分类、检测、翻译、OCR 这种判别式小任务,TFLite/LiteRT 是当下最优解;生成式、要持续热更新、对精度极度敏感的任务,老实上云。别为了”纯本地”的理念,把体验做脆弱。

现在就能动手

  1. 去 TensorFlow 官网模型库下载 mobilenet_v1_1.0_224_quant.tflite(约 4.3MB)和 labels 文件,扔进 app/src/main/assets
  2. 加依赖 org.tensorflow:tensorflow-lite + tensorflow-lite-support,按上面的代码写出单例 Interpreter,先 CPU 跑通一张图的分类
  3. 打开 NNAPI delegate,对比 CPU 和 delegate 的推理耗时(用 SystemClock.elapsedRealtime() 打点),亲眼看到 2–3 倍加速
  4. 故意把归一化参数写错一次(比如量化模型套 float 归一化),看输出如何全错——这个坑亲手踩一遍比看十遍记得牢
  5. 把推理包进 withContext(Dispatchers.Default),用 Android Studio 的 Profiler 确认主线程帧率不受影响

常见问题

哪些场景适合用本地模型?

图片去水印、OCR 辅助、离线翻译、文本分类这类任务。一旦能在设备本地完成,延迟从秒级掉到毫秒级,隐私边界也更清晰,没网时产品依然成立。

为什么选 TFLite?

不是因为它最先进,而是足够工程化:模型体积、推理速度、设备兼容性、Android / iOS 集成路径都摆在台面上。现在它改名叫 LiteRT,API 基本无缝迁移。

TFLite 最大的坑在哪?

模型前后处理:归一化参数必须和训练时一字不差,量化模型吃 uint8 别套 float 归一化,颜色通道 RGB/BGR 别搞反。这些地方一错,结果全失真,而且不报错——静默地错,最气人。

本地推理的性能优化要点是什么?

四条:模型加载只做一次(单例+预热);delegate 能开就开(NNAPI/GPU,失败回退 CPU);前处理复用 ByteBuffer,少做 bitmap 拷贝;推理扔后台线程,UI 只消费状态。

什么时候不该用本地模型?

模型太大(APK 体积顶不住)、精度要求极高(差 1 个点都不行)、需要持续热更新(今天上线明天就换模型)。好方案应该是场景驱动,而不是理念驱动。

量化会掉多少精度?

int8 量化通常体积砍到 1/4,精度掉 1–2 个点。对分类、翻译这类任务完全可接受;对精度极度敏感的任务,先做量化感知训练再上。

本篇的 X 速览版

1/ 高铁穿隧道没信号,想查”红烧狮子头”英文怎么说——离线翻译包救了我。那一刻我决定把 AI 搬进手机本地:延迟从 1 秒掉到 30ms,没网照样跑 🧵 2/ 先算账:云端一次请求 = 网络 RTT 300–800ms + 推理 200–500ms,轻松破 1 秒还怕没网。本地 = 前处理 10ms + 推理 30ms + 后处理 5ms,端到端 120ms 内。 3/ 第一道门槛:模型体积。int8 量化把 FP32 砍到 1/4,精度只掉 1–2 个点。MobileNetV1 量化后 4.3MB,离线翻译模型 30MB——这个量级才配进安装包。 4/ 第二道门槛:速度。纯 CPU 约 55ms,NNAPI/GPU delegate 能压到 18ms,快 2–3 倍。delegate 失败自动回退 CPU,所以策略是”能开就开,开不了拉倒”。 5/ 第三道门槛:前后处理,TFLite 真正的坑王。归一化参数必须和训练时一字不差;量化模型吃 uint8,你把 float 归一化套上去,输出静默全错,还不报错——最气人。 6/ 四条优化铁律:模型只加载一次(单例+启动预热);delegate 优先;前处理复用同一块 ByteBuffer;推理扔 Dispatchers.Default,UI 只消费状态。 7/ 实测:分类端到端 120ms 内;翻译首包 400ms 后每句 20–40ms;去水印 512 图约 200ms。APK 只大 4–30MB。 8/ 今晚就能动手:① 下载 mobilenet quant 模型扔 assets ② 单例 Interpreter CPU 跑通 ③ 开 NNAPI 亲眼看 2–3 倍加速 ④ 故意写错归一化看它怎么错 ⑤ Profiler 确认主线程不掉帧。 9/ 判断标准:判别式小任务(分类/检测/翻译/OCR)本地是最优解;生成式、要热更新、精度极度敏感的上云。场景驱动,别为理念把体验做脆弱。全文:https://citygenius-blog.pages.dev/article/local-ai-tflite