PyBox / Blog / Machine learning

Run AI models on Android with Python (ONNX, TFLite, PyTorch)

Inference on the device keeps data private and works offline. Here is how the main runtimes fit together.

Run AI models on Android with Python (ONNX, TFLite, PyTorch): the PyBox screen this guide uses
PyBox is the Python IDE I build. Everything below works with it, and the steps are the same ideas you would use anywhere. Get it on Google Play.

Pick a runtime

  • ONNX Runtime: a good default. Export your model to ONNX from PyTorch or another framework.
  • TensorFlow Lite: small, fast, built for mobile.
  • NCNN: lean, mobile-first, popular for vision models.
  • PyTorch: when you need to train or fine-tune a little, or run research code unchanged.
  • llama.cpp: local language models in GGUF format through its Python binding.

An ONNX example

import numpy as np
import onnxruntime as ort

session = ort.InferenceSession("model.onnx")
name = session.get_inputs()[0].name
x = np.random.rand(1, 3, 224, 224).astype(np.float32)

outputs = session.run(None, {name: x})
print(outputs[0].shape)

Replace model.onnx with a real exported model, put it in the project folder, and run.

Speech and vision

PyBox starter projects include Vosk Live Transcription for offline speech to text, and a NCNN Image Classifier. sherpa-onnx covers speech recognition and synthesis through ONNX.

Local language models

There is an ONNX Runtime LLM Chat starter project that runs Qwen. Use a small quantized model first. Speed depends on the device, the model size and the quantization.

Tips

  • Quantize models to int8 where accuracy allows.
  • Keep the model file on internal storage.
  • Measure with a few warm-up runs before you time anything.

See Python libraries on Android.

Questions

Can I run PyTorch on Android with Python?

Yes. PyBox provides PyTorch, torchvision and torchaudio as Android wheels.

Is there GPU acceleration for inference?

TensorFlow, NCNN and ONNX Runtime can use GPU acceleration. Speed depends on the device and the model.

Anshuman MishraBuilds PyBox at Vytros, a Python IDE for Android. About the developer.

Code Python on your phone.