惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
人人都是产品经理
人人都是产品经理
Martin Fowler
Martin Fowler
D
Docker
F
Full Disclosure
Recent Announcements
Recent Announcements
MyScale Blog
MyScale Blog
美团技术团队
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog
A
About on SuperTechFans
IT之家
IT之家
P
Proofpoint News Feed
有赞技术团队
有赞技术团队
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
雷峰网
雷峰网
WordPress大学
WordPress大学
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 【当耐特】
V
Visual Studio Blog
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
Microsoft Security Blog
Microsoft Security Blog
U
Unit 42
腾讯CDC
Stack Overflow Blog
Stack Overflow Blog
B
Blog RSS Feed
I
InfoQ
N
Netflix TechBlog - Medium
博客园 - 三生石上(FineUI控件)
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Vercel News
Vercel News
月光博客
月光博客
F
Fortinet All Blogs
Google DeepMind News
Google DeepMind News
小众软件
小众软件
Recorded Future
Recorded Future
博客园 - Franky
Blog — PlanetScale
Blog — PlanetScale
云风的 BLOG
云风的 BLOG
C
Check Point Blog
博客园 - 叶小钗
GbyAI
GbyAI
M
MIT News - Artificial intelligence
博客园 - 司徒正美

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Gemma 4 on Android: Tricks for Faster On-Device Inference
IBIYEMI Samu · 2026-05-24 · via DEV Community

When I tried building an on-device AI app with Gemma 4, the pitch was clear: model weights on the device, no server, no API calls, works offline. Getting it to actually run fast was a different problem.

This post covers what I learned working with LiteRT-LM 0.12.0 and Gemma 4 E2B on Android in Kotlin. Some of it is configuration. Some of it is understanding what the bottleneck actually is before reaching for a fix. If you're building with Gemma 4 E2B on Android and inference feels too slow to ship, here are the tricks that actually helped.

1. Basic Setup

Add the dependency:

// build.gradle
implementation("com.google.ai.edge.litertlm:litertlm-android:0.12.0")

Enter fullscreen mode Exit fullscreen mode

The model file itself comes from Hugging Face. The litert-community/gemma-4-E2B-it-litert-lm repository hosts the .litertlm format that LiteRT-LM expects. This is not a GGUF file. Using the wrong format will cause a silent failure on model load, so confirm the file extension before downloading.

The model is gated on Hugging Face, so you'll need an access token. A read token is enough. If your app handles the download directly (via DownloadManager or a similar mechanism), pass the token as an Authorization header in the request rather than entering it interactively. The full LiteRT-LM Android API reference is here.

Initialize the engine:

val options = LlmInferenceOptions.builder()
    .setModelPath(modelPath)
    .setMaxTokens(512)
    .setTopK(40)
    .setTemperature(0.8f)
    .setRandomSeed(101)
    .build()

val llmInference = LlmInference.createFromOptions(context, options)

Enter fullscreen mode Exit fullscreen mode

2. GPU Backend and Why It Silently Falls Back to CPU

LiteRT-LM supports three backends: CPU, GPU (via OpenCL), and NPU. GPU is where you get meaningful speed on Android.

The problem is that OpenCL support is not universal. Mid-range and budget chips from Qualcomm and MediaTek often don't expose OpenCL to the Android application layer. If you initialize with Backend.GPU() on one of these devices, the engine falls back to CPU without throwing an error by default.

If you don't log this, you'll spend time optimizing prompts thinking you're on GPU when you're not.

Check which backend actually initialized:

try {
    val config = EngineConfig.builder()
        .setModelPath(modelPath)
        .setBackend(Backend.GPU())
        .build()
    engine = Engine(config)
    Log.d("Inference", "GPU backend initialized")
} catch (e: Exception) {
    val config = EngineConfig.builder()
        .setModelPath(modelPath)
        .setBackend(Backend.CPU())
        .build()
    engine = Engine(config)
    Log.d("Inference", "CPU fallback: ${e.message}")
}

Enter fullscreen mode Exit fullscreen mode

On CPU with Gemma 4 E2B, expect roughly 2 to 5 tokens per second on mid-range hardware. On GPU-capable devices via OpenCL, LiteRT-LM benchmarks show around 52 tokens per second on a Samsung S26 Ultra. The delta between CPU and GPU is not incremental, it is a different category of usability.

If your target users are running budget Android devices, plan your UX around CPU speeds. Streaming tokens as they arrive, showing a "thinking" indicator early, and capping output length all reduce how slow it feels even when the hardware is constrained.

One more thing on backends: NPU initialization is not just a silent fallback situation. On some devices, attempting Backend.NPU() can cause a native process crash (SIGKILL or SIGSEGV) due to driver fragmentation across Android hardware. If you want to expose NPU as an option, treat it as an experimental toggle rather than a default path, and always have the GPU-to-CPU chain as the safe baseline.

3. Prefill Is the First Bottleneck, Not Decoding

Most discussions about LLM inference speed focus on decode speed (tokens per second). On mobile, the more immediate pain point is often prefill: the time before the model generates the first token.

Prefill is proportional to the size of your input prompt. Every character you inject into the system prompt has to be processed before generation starts. If you're doing context injection (pasting a document or manual into the prompt), this cost hits on every single query.

A rough example. A 50,000 character document injected into a system prompt is approximately 12,000 to 15,000 tokens. On CPU, processing that input alone takes several seconds before the model produces anything. A user taps submit and waits in silence.

Gemma 4 E2B supports a 128K context window, and that number is real. But mobile hardware is bound by prefill latency and KV cache limits long before you hit 128K. The theoretical capacity and the practical ceiling on a 4GB device are very different numbers.

Practical fixes:

Set a hard character budget on injected context and enforce it at the application layer:

val contextBudget = 6000 // characters, not tokens
val injectedContext = sourceDocument.take(contextBudget)

Enter fullscreen mode Exit fullscreen mode

6,000 characters is roughly 1,500 tokens. That's enough context to be useful for most domain-specific queries while keeping prefill manageable on CPU.

If you're building a document Q&A feature, extract only the relevant section rather than injecting the full document. A keyword match or simple sentence scoring function in Kotlin can identify the most relevant passage and inject that instead of the whole file. This is not full RAG. It's a practical middle ground that works without vector databases.

4. Multi-Token Prediction: The Feature That Makes Gemma 4 Worth It on Mobile

Multi-Token Prediction (MTP) is one of the things that genuinely sets Gemma 4 apart from earlier versions for on-device use. It was introduced with the Gemma 4 model family specifically, and it changes what's achievable on mobile hardware in a meaningful way.

Standard autoregressive inference generates one token per forward pass. The processor moves model parameters from memory to compute units, generates one token, then does it again. On mobile hardware, the data movement cost dominates over the actual computation.

MTP uses speculative decoding to work around this. A lightweight drafter model proposes several tokens ahead of time. The primary model then verifies those proposals in a single parallel forward pass. If the proposed tokens are correct, the model accepts them all plus generates one more. If the drafter was wrong at some position, it rejects from that point and takes over. Output quality doesn't change because the primary model has final say over every token.

LiteRT-LM bundles the MTP drafter inside the same .litertlm model artifact. Both models run on the same hardware backend, sharing KV cache in local memory. This avoids the cross-device data transfer overhead that would otherwise cancel out part of the gain.

Google's benchmarks show up to a 2.2x decode speedup with MTP enabled on the GPU backend. See their full breakdown here. For the dedicated MTP announcement and how the drafter was designed for the Gemma 4 family specifically, see this post. Enabling it is two lines of configuration:

val options = LlmInferenceOptions.builder()
    .setModelPath(modelPath)
    .setMaxTokens(512)
    .setUseMtp(true)       // enable MTP drafter
    .setTopK(40)
    .setTemperature(0.8f)
    .build()

Enter fullscreen mode Exit fullscreen mode

The gains are more pronounced for predictable completions. For creative or open-ended generation where the drafter has low acceptance rates, the speedup is smaller. For structured or domain-constrained outputs, acceptance rates are higher and the gains are closer to the ceiling.

One important caveat: if you're on CPU, disable MTP. The 2.2x gain assumes parallel GPU execution where the drafter and target model run simultaneously. On CPU they run sequentially, and the overhead of running two models back to back outweighs the benefit. Check which backend actually initialized before deciding whether to enable it.

val useMtp = backend == Backend.GPU() // only enable on GPU
val options = LlmInferenceOptions.builder()
    .setModelPath(modelPath)
    .setUseMtp(useMtp)
    .build()

Enter fullscreen mode Exit fullscreen mode

5. Thinking Mode: When to Use It and When Not To

Gemma 4 supports a reasoning mode where the model generates an internal scratchpad before producing its final response. LiteRT-LM exposes this directly. The reasoning output appears between <|think|> and </think> tags in the stream.

Thinking mode improves output quality for multi-step or diagnostic tasks. It costs tokens. On CPU, those extra 200 to 400 reasoning tokens represent meaningful latency before the user sees a final answer.

The practical approach: enable thinking on tasks where accuracy matters, disable it on conversational turns where it doesn't.

fun buildSystemPrompt(requiresReasoning: Boolean): String {
    return if (requiresReasoning) {
        "<|think|> You are a diagnostic expert. Think through this step by step before answering."
    } else {
        "You are a helpful assistant. Answer clearly and concisely."
    }
}

Enter fullscreen mode Exit fullscreen mode

If you're displaying the thinking stream in the UI (as a visible "reasoning" component), the latency becomes part of the experience rather than dead time. The user sees the model working. This matters more on CPU where the stream is slow enough to read.

If you strip thinking tokens before displaying the response, you're paying the token cost with no UX return. In that case, disable it.

6. Constrained Decoding for Structured Output

LiteRT-LM supports constrained decoding, which enforces a JSON schema on the model's output. Instead of parsing free text and hoping the model follows your format instructions, you define the schema and the engine guarantees compliance.

This is useful for any feature that needs to render structured results rather than prose. A diagnosis card, a checklist, a decision tree. The model produces valid JSON every time.

val schema = """
{
  "type": "object",
  "properties": {
    "diagnosis": { "type": "string" },
    "confidence": { "type": "string", "enum": ["high", "medium", "low"] },
    "action": { "type": "string" },
    "escalate": { "type": "boolean" }
  },
  "required": ["diagnosis", "confidence", "action", "escalate"]
}
"""

val options = LlmInferenceOptions.builder()
    .setModelPath(modelPath)
    .setResponseSchema(schema)
    .setMaxTokens(300)
    .build()

Enter fullscreen mode Exit fullscreen mode

The max tokens value matters here. A constrained JSON response is short. Setting a generous 2,000 token budget for a response that will always be under 100 tokens keeps the KV cache allocated longer than necessary. Set it tight.

7. Session Save and Restore

LiteRT-LM supports serializing and restoring the KV cache state across sessions. For applications with persistent context (a long document loaded once, or a multi-turn workflow), this means the prefill phase only happens once. On return sessions, the engine restores the cached state and skips the expensive input processing step.

For document Q&A specifically, this is worth implementing. The user loads a document, the prefill runs once and the state is serialized to disk. Every subsequent question in that session resumes from the cached state rather than reprocessing the document from scratch. The Google AI Edge Gallery app is the most complete open-source example of session management in a real LiteRT-LM application.

Summary

Technique Where it helps Implementation cost
Log GPU vs CPU backend Debugging, avoiding silent CPU fallback Low
Reduce injected context Prefill speed Low
Enable MTP Decode speed on GPU-capable devices Very low (two lines)
Conditional thinking mode Balancing quality vs latency per task Low
Constrained decoding Structured output reliability and token efficiency Medium
Session save/restore Repeated queries against same context Medium

The model download is the upfront cost. After that, LiteRT-LM gives you enough knobs to tune inference for the specific hardware and use case you're targeting. The techniques above don't require changes to model weights or training. They're all configuration and prompt engineering decisions available in 0.12.0.


For the full LiteRT-LM technical deep-dive from the Google AI Edge team, including iOS and WebGPU benchmarks, read the official post.