🤖 AI Hot

Google LiteRT.js: Run AI Models in the Browser With WebGPU

A
Alex Chen

Google released LiteRT.js in July 2026, and it solves a problem that’s been bugging me for years. Running machine learning models in the browser has always been a compromise. TensorFlow.js works, but it’s slow for anything beyond toy models. ONNX Runtime Web is better, but the API is finicky and debugging is painful. WebAssembly helps, but CPU-only inference caps what you can do.

LiteRT.js changes the equation by giving you hardware-accelerated inference through WebGPU, with WebNN support on the roadmap. It runs .tflite models directly — the same format used by TensorFlow Lite on mobile and edge devices. If you’ve got a model that runs on Android or an embedded device, it now runs in Chrome too, often at speeds that rival native execution.

The practical implication: you can now ship AI features in web apps without a server-side inference pipeline. Image classification, object detection, text embedding, even small language models all run client-side. No API keys, no latency, no per-request costs.

What LiteRT.js actually is

LiteRT.js is part of Google’s AI Edge ecosystem, which includes tools for on-device ML across platforms. The full stack looks like this:

  • LiteRT (core runtime): C++ inference engine that runs .tflite models on mobile, embedded, and now web
  • LiteRT Torch Converter: Converts PyTorch models to .tflite format
  • LiteRT Torch Generative API: Library for adapting LLMs to run efficiently on edge
  • LiteRT-LM: Optimized LLM inference for edge platforms
  • LiteRT.js: JavaScript bindings for the LiteRT runtime, targeting production web apps

The architecture uses three backends, selected automatically or manually:

BackendHardwareSpeedAvailability
XNNPACK (CPU)CPU via WASM SIMDBaselineAll browsers
ML Drift (GPU)GPU via WebGPU2-5x fasterChrome 113+, Edge 113+
WebNN (NPU)NPU via WebNN APIFastestExperimental, Chrome Canary

The ML Drift backend is where the magic happens. It maps LiteRT operations onto WebGPU compute shaders, giving you GPU acceleration without leaving the browser sandbox. For models with heavy matrix multiplication (transformers, CNNs), the speedup over CPU is dramatic — Google’s benchmarks show 3x improvements on typical vision models and 2-4x on text embedding.

Getting started in 5 minutes

The setup is refreshingly simple compared to TensorFlow.js. No build system required for basic usage.

<!DOCTYPE html>
<html>
<head>
  <script type="module">
    import { LiteRT } from 'https://cdn.jsdelivr.net/npm/@google-ai-edge/litert@latest/dist/litert.min.js';

    async function runInference() {
      // Load a .tflite model
      const rt = new LiteRT();
      await rt.loadModel('/models/mobilenet_v2.tflite');

      // Run inference on an image
      const input = document.getElementById('input-image');
      const result = await rt.run(input);

      console.log('Top prediction:', result[0]);
    }
  </script>
</head>
<body>
  <img id="input-image" src="cat.jpg" />
  <button onclick="runInference()">Run</button>
</body>
</html>

For production use with a bundler:

npm install @google-ai-edge/litert
import { LiteRT, Backend } from '@google-ai-edge/litert';

const rt = new LiteRT({
  backend: Backend.WebGPU,  // Force GPU backend
  maxThreads: 4,
  warmupRuns: 2,
});

await rt.loadModel('/models/efficientnet-lite4.tflite');

// Pre-allocate tensor for repeated inference
const inputTensor = rt.createTensor('float32', [1, 224, 224, 3]);

// Reuse tensor across calls to avoid allocation overhead
const output = await rt.run(inputTensor);

The API is deliberately minimal. You create a runtime, load a model, and call rt.run(). No graph building, no session management, no memory pooling to configure. Google clearly optimized for the “I just want this to work” use case.

Converting models for LiteRT.js

If you already have models in PyTorch or TensorFlow, converting them to .tflite is straightforward.

From PyTorch:

pip install ai-edge-torch-converter

# Convert a PyTorch model
ai-edge-torch-converter \
  --model-path model.pt \
  --output model.tflite \
  --input-shape "1,3,224,224" \
  --quantize int8

From TensorFlow/Keras:

import tensorflow as tf

model = tf.keras.models.load_model('my_model.h5')

converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_ops = [
    tf.lite.OpsSet.TFLITE_BUILTINS,
    tf.lite.OpsSet.SELECT_TF_OPS,
]
tflite_model = converter.convert()

with open('my_model.tflite', 'wb') as f:
    f.write(tflite_model)

The converter supports INT8 and FP16 quantization. For browser deployment, I’d recommend INT8 — the model files are smaller (50-75% reduction), download faster, and WebGPU handles INT8 operations efficiently. FP16 gives slightly better accuracy but doubles file size with minimal quality gains for most vision and embedding models.

What you can actually run

Not everything runs well in the browser. Here’s what works today and what doesn’t.

Works well (sub-100ms inference):

  • Image classification (MobileNet, EfficientNet-Lite)
  • Object detection (SSD MobileNet, YOLO-Nano)
  • Text embedding (Universal Sentence Encoder Lite, small BERT variants)
  • Pose estimation (MoveNet, PoseNet)
  • Image segmentation (DeepLab, MediaPipe variants)
  • Face detection and landmarking

Works with caveats (100ms-1s inference, depends on GPU):

  • Small language models (Gemma 2B, Phi-3-mini with quant)
  • Text-to-image (Stable Diffusion with heavy optimization)
  • Speech recognition (Whisper tiny/small)
  • Super-resolution models

Not practical yet:

  • Large language models (7B+ parameters)
  • Real-time video processing at full resolution
  • Training or fine-tuning (LiteRT is inference-only)

The sweet spot right now is vision models under 15MB and text embedding models under 50MB. These give you sub-100ms inference on any device with a GPU, and sub-300ms on CPU-only devices. For web apps that need content moderation, visual search, or semantic search, this is already production-ready.

Comparing LiteRT.js with the alternatives

FeatureLiteRT.jsTensorFlow.jsONNX Runtime WebTransformers.js
Model format.tfliteTF.js GraphModel.onnxONNX/HF
WebGPU support✅ Native⚠️ Limited✅ Good⚠️ Via ONNX
File size (runtime)~400KB~800KB+~600KB~1.5MB+
Mobile ↔ Web model sharing✅ Same .tflite❌ Different format⚠️ Manual❌
INT8 quant support✅ First-class✅✅⚠️
NPU (WebNN) support✅ Planned❌❌❌
Bundle size after tree-shaking~200KB~500KB~300KB~800KB

LiteRT.js’s main advantage over TensorFlow.js is model format compatibility. If you already use TensorFlow Lite for mobile, the exact same .tflite file works in the browser. No conversion, no separate model pipeline. For teams shipping AI features across iOS, Android, and web, this eliminates a significant maintenance burden.

Compared to ONNX Runtime Web, LiteRT.js is simpler but less flexible. ONNX supports more model architectures and has a bigger ecosystem of pre-converted models on Hugging Face. But ONNX’s WebGPU backend requires careful configuration, and debugging ONNX graph errors in the browser is genuinely painful. LiteRT.js trades some flexibility for reliability.

Transformers.js (Hugging Face’s browser library) has the best model selection — thousands of pre-converted models on the Hub. But it’s also the slowest, relying on ONNX Runtime Web under the hood with an additional abstraction layer. For quick prototyping, Transformers.js wins. For production deployment where every millisecond counts, LiteRT.js is the better choice.

Pitfalls I ran into

Setting up my first LiteRT.js project, I hit a few things that aren’t obvious from the docs.

WebGPU isn’t available everywhere. Chrome and Edge support it. Firefox has it behind a flag. Safari doesn’t support it at all as of mid-2026. If you need cross-browser coverage, plan for a CPU fallback. The rt.backend property tells you which backend actually loaded — check it after loadModel().

First inference is always slow. WebGPU shader compilation happens lazily on the first call. Google added a warmupRuns option that burns this cost at initialization. Set it to 2-3 and your actual inference calls will be fast. Without warmup, that first rt.run() can take 2-3 seconds for complex models.

The .tflite format has opset limitations. Not every TensorFlow op has a TFLite equivalent. If your model uses tf.while_loop, dynamic control flow, or certain string ops, conversion will fail. Google is expanding the op coverage with each release, but for now, stick to the ops listed in the TFLite builtin ops documentation.

Memory management is manual in a subtle way. LiteRT.js doesn’t garbage-collect tensors automatically — they’re WebGPU buffers, not JavaScript objects. If you create a new tensor for every inference call and never release them, you’ll hit out-of-memory errors after a few hundred calls. Use rt.createTensor() once and reuse it, or call tensor.dispose() when you’re done.

Chrome’s WebGPU implementation is still evolving. I’ve seen different behavior between Chrome stable and Canary, especially around buffer synchronization. Test on your target Chrome version and lock your dependency versions.

A real-world example: client-side image moderation

Here’s a complete example that uses LiteRT.js to moderate user-uploaded images before they hit your server:

import { LiteRT, Backend } from '@google-ai-edge/litert';

class ImageModerator {
  constructor() {
    this.rt = new LiteRT({
      backend: Backend.Auto,
      warmupRuns: 3,
    });
    this.loaded = false;
  }

  async init() {
    await this.rt.loadModel('/models/nsfw-detector.tflite');
    this.loaded = true;
  }

  async checkImage(file) {
    if (!this.loaded) await this.init();

    // Resize and normalize image to model input size
    const img = await this.preprocessImage(file, 224, 224);
    const result = await this.rt.run(img);

    // Typical output: [safe_prob, nsfw_prob]
    const isSafe = result[0] > 0.85;
    return {
      safe: isSafe,
      confidence: result[0],
      flagged: !isSafe && result[0] < 0.5,
    };
  }

  async preprocessImage(file, width, height) {
    const bitmap = await createImageBitmap(file, {
      resizeWidth: width,
      resizeHeight: height,
    });
    // LiteRT handles the normalization internally based on model metadata
    return bitmap;
  }

  dispose() {
    this.rt.dispose();
  }
}

// Usage
const moderator = new ImageModerator();
await moderator.init();

document.getElementById('upload').addEventListener('change', async (e) => {
  const result = await moderator.checkImage(e.target.files[0]);
  if (!result.safe) {
    alert('This image was flagged by automated moderation.');
    return;
  }
  // Proceed with upload
});

The whole thing runs in under 50ms on a modern laptop with WebGPU. No server roundtrip, no cost per scan, and the user’s image never leaves their device. For privacy-sensitive applications like photo sharing or dating apps, this pattern is compelling.

When not to use LiteRT.js

Some situations where you’re better off with a server-side approach:

Large models (>50MB). Downloading a 200MB .tflite file over a mobile connection is a bad user experience. If your model is big, server-side inference with streaming is better.

Consistent performance requirements. Browser GPU availability varies wildly. Your MacBook Pro user gets sub-50ms inference. Your budget Android phone user runs everything on CPU at 500ms. If you need predictable latency, run inference on your own hardware.

Model IP protection. TFLite models can be extracted from the browser bundle. If your model weights are proprietary and valuable, running them client-side means giving away your IP.

Multi-model pipelines. If you’re chaining multiple models (detect → crop → classify), the per-model overhead adds up. On a server with GPU persistence, you can batch and pipeline these operations more efficiently.

Where this is heading

LiteRT.js feels like an inflection point for browser-based ML. The combination of a mature model format (.tflite), hardware acceleration (WebGPU), and a simple API hits the sweet spot that previous solutions missed. I expect we’ll see a wave of web apps adding client-side AI features that were previously server-only — semantic search, visual similarity, real-time translation, content moderation.

The WebNN backend is the next big unlock. When browsers start exposing NPUs (neural processing units — dedicated AI accelerators in newer chips like Qualcomm’s Hexagon and Apple’s Neural Engine), client-side inference will hit single-digit millisecond latency for many models. Google has been pushing the WebNN standard at W3C, and Chrome Canary already has experimental support.

For now, the pragmatic take: if you’re building web apps and have been avoiding client-side AI because the tooling was too painful, give LiteRT.js a weekend. The setup is fast, the performance on WebGPU is real, and the .tflite ecosystem means you’re not locked into a web-only model pipeline. It’s the first browser ML runtime I’ve used that doesn’t feel like a compromise.

Disclosure: CarCare Guide is reader-supported. When you buy through links on our site, we may earn an affiliate commission at no extra cost to you. Learn more.
A
Alex Chen