GNN + MediaPipe LLM inference API for Android code completion
Meta description: Wire a Graph Neural Network to MediaPipe’s LLM Inference API for on-device code completion — covering AST retrieval, embedding fusion, and KV-cache reuse.
TL;DR
You can run a credible on-device code completion pipeline on a Pixel 9 by pairing a lightweight GNN for AST-aware context retrieval with a quantized LLM decoder via MediaPipe’s LLM Inference API. The key is fusing GNN node embeddings into the LLM’s token embedding layer before the first transformer block, then reusing the KV-cache across GNN-retrieved snippets to avoid redundant prefill passes. Done right, the full pipeline fits under 200MB on Snapdragon 8 Gen 3.
The architecture at a glance
Most teams treat the on-device LLM as a black box and then wonder why context quality is poor. Structure-aware context retrieval fixes this, and that’s what a GNN over the Abstract Syntax Tree gives you.
The pipeline has three stages:
- GNN pass: Parse the open file into an AST, run a small graph network over it to produce per-node embeddings, retrieve the top-k structurally relevant snippets from a local embedding index.
- Embedding fusion: Project GNN node embeddings into the LLM’s token embedding space and inject them before the first transformer block.
- Incremental decoding: Feed the fused context into MediaPipe’s LLM Inference API and stream tokens back, reusing cached KV pairs across retrieved snippets.
GNN-driven AST context retrieval
A standard BM25 retriever treats code as a bag of tokens. A GNN sees that a suspend fun calling a Flow collector is structurally different from a plain lambda, even if the token overlap is high.
A 3-layer GraphSAGE network with 128-dimensional hidden states is sufficient. Keep the GNN frozen after offline training; you don’t want backprop happening at inference time on-device.
// Serialize AST edges for TFLite GNN input
val edgeIndex = astGraph.edges.flatMap { listOf(it.src, it.dst) }.toIntArray()
val nodeFeatures = astGraph.nodes.map { it.tokenEmbedding }.toFloatArray()
val gnnInterpreter = Interpreter(gnnModel)
gnnInterpreter.run(mapOf(0 to nodeFeatures, 1 to edgeIndex), outputEmbeddings)
The output is a [k, 128] tensor of snippet embeddings. These get nearest-neighbor searched against a pre-built mobile-adapted FAISS index (no GPU index, flat L2 search) stored in the app’s files directory.
Embedding fusion at the token layer
MediaPipe’s LlmInference API doesn’t natively expose an embedding injection hook, so fusion happens at the prompt level using a learned linear projection. Project GNN embeddings to the LLM’s token dimension (typically 2048 for a 1B-parameter model), serialize them as special prefix tokens, and prepend them to the prompt string before inference.
val projectedContext = gnnProjectionMatrix.dot(gnnEmbeddings) // [k, 2048]
val contextTokens = projectedContext.toSpecialTokenString()
val fullPrompt = contextTokens + "\n" + userCursorContext
llmInference.generateResponseAsync(fullPrompt, resultListener)
The projection matrix is a small [128, 2048] float16 array (roughly 512KB), trained offline to align GNN and LLM representation spaces.
KV-cache reuse across retrieved snippets
The expensive part of LLM inference is prefill: processing the prompt tokens through all transformer layers. If you retrieve five snippets, naively prefilling all five for every keystroke is a latency killer.
The solution is a prefix KV-cache: pre-compute and cache the KV pairs for each retrieved snippet independently, then compose the final prompt by concatenating cached KV blocks. Structure your retrieved snippets as stable session prefixes and only run incremental decoding on the new cursor context delta.
// Pre-build a session over the stable retrieved context
val prefixSession = LlmInference.createSession(context, options)
retrievedSnippets
.sortedBy { it.structuralDistance } // most stable snippets first
.forEach { snippet -> prefixSession.addQueryChunk(snippet.asContextToken()) }
// Only the cursor delta triggers a new decode pass
prefixSession.addQueryChunk(cursorDelta)
prefixSession.generateResponseAsync { partialResult, done ->
if (done) streamToEditor(partialResult)
}
Sorting by structural distance from the cursor node ensures the most stable snippets anchor the prefix. These are cached longest and evicted last if the session window fills.
Memory budget on Snapdragon 8 Gen 3
| Component | Model size | Runtime RSS |
|---|---|---|
| GNN (GraphSAGE 3-layer) | 4 MB | ~18 MB |
| Mobile-adapted FAISS index (10k snippets) | 12 MB | ~20 MB |
| GNN projection matrix | 0.5 MB | ~1 MB |
| LLM (Gemma 2B INT4 via MediaPipe) | 1.1 GB on disk | ~140 MB active¹ |
| KV-cache (512 token window) | — | ~16 MB |
| Total pipeline | ~195 MB |
¹ Gemma 2B INT4 uses memory-mapped weight loading: weights remain on disk and only the active transformer layers are paged into RAM during a given inference pass. The 1.1 GB figure is the full model on disk; ~140 MB reflects the working set for a 512-token window.
Snapdragon 8 Gen 3 gives you ~12 TOPS of NPU headroom. With INT4 quantization and GPU delegate enabled in MediaPipe, a 128-token completion completes in roughly 400–600ms — perceptible but acceptable for a background suggestion panel.
Conclusion
Memory budget is the primary ship/no-ship gate for on-device inference features. This pipeline lands under 200MB because each component is sized for its job: the GNN is small and fast, the projection is minimal, and the LLM does only incremental decoding.
Three things that actually matter when shipping this:
- Freeze your GNN at inference time. Train offline, export to TFLite, run it as a pure feature extractor. Dynamic training on-device is a memory and latency trap.
- Sort snippets by structural distance before building the KV-cache prefix. The most stable snippets should anchor earliest so they’re cached longest.
- Plan for INT4 quantization from the start, not as a last-minute size reduction. INT8 gets you a smaller model; INT4 gets you enough headroom to run the GNN and projection layer alongside it.
#android #mobile #architecture #kotlin