LiteRT Torch Documentation
repository·main·Indexed 21 days ago
https://github.com/google-ai-edge/litert-torchA Python library for converting PyTorch models into .tflite format for efficient on-device execution on Android, iOS, and IoT devices via LiteRT. It includes tools for standard model conversion, generative/transformer-based model optimization, and quantization using PT2E (via torchao) or TensorFlow Lite flags. The library supports multi-signature conversion, NHWC layout transformation, and provides debugging tools like find_culprits. It also includes specialized workflows for converting and quantizing Gemma 3 models for use with the MediaPipe LLM Inference API.
What's inside LiteRT Torch
- The LiteRT Torch Generative API is an end-to-end solution designed to simplify the deployment of Small Language Models (SLMs) and Large Generative Models (LGMs) on-device. It addresses the complexities of optimizing generative models for mobile and web platforms by providing tools for model quantization, numerical debugging, quality assessment, and performance tuning. The library aims to provide a PyTorch-centric authoring experience that integrates with the TF Lite runtime for efficient on-device execution.
Overview of LiteRT Torch
mainLiteRT Torch provides tools to convert PyTorch models into the LiteRT (.tflite) format. It includes a PyTorch Converter for model transformation and a Generative API for working with generative models.Overview of LiteRT Torch Generative API
mainThe LiteRT Torch Generative API provides PyTorch-native building blocks for composing Transformer models (like Gemma or TinyLlama) using mobile-friendly abstractions. This ensures models can be converted and executed performantly on the LiteRT mobile runtime.
Note: This is currently v0.1 (early developer preview). The API is unstable and subject to change.
Typical Workflow:
- Start with a trained PyTorch LLM (e.g., from Hugging Face or Kaggle).
- Re-author the model using Edge Generative API layers to ensure mobile compatibility.
- Quantize the model to reduce size and improve performance.
- Verify implementation and quality using your evaluation pipeline.
- Convert the model to a LiteRT Flatbuffer.
- Deploy using either the LiteRT Runtime APIs (for maximum control) or the MediaPipe LLM Inference API (for ease of use).
LiteRT LLM Calibration & Quantization Skill Overview
mainThe
litert-quantization-calibskill is designed to assist in calibrating, merging, and statically quantizing LiteRT LLM models (such as Gemma 3) for high-performance NPU deployments.Use this skill when:
- Calibrating a LiteRT model against conversational prompt datasets.
- Merging calibration JSON files from multiple tasks.
- Statically quantizing model suites (e.g., A8W8 or A16W8 configurations).
- Protecting sensitive layers (like RMS Norm or residual paths) in Float32 to prevent quantization noise.
- Aligning KV Cache quantization scaling parameters across main and auxiliary models.
- Running CPU/NPU inference testing on unquantized or quantized LiteRT models.
Do NOT use this for:
- Quantizing non-LiteRT models (e.g., native PyTorch, JAX, or ONNX models).
- General quantization tasks that do not involve LLM prefill/decode subgraphs or KV caches.
Use ODML Transformer Layers to re-author models
mainThelitert_torch.generative.layersmodule provides common PyTorch building blocks designed to help you re-author transformer models for LiteRT. It includes specialized attention mechanisms, feed-forward layers, normalization modules, and KV cache implementations optimized for performance.What is the LiteRT Torch Generative API?
mainThe Generative API (currently in Alpha) is a Torch-native library designed for authoring mobile-optimized PyTorch Transformer models. It enables the conversion of models into LiteRT-LM models, which are optimized for deploying Large Language Models (LLMs) on edge devices.
Key Features:
- Optimization: Supports model authoring and quantization to improve on-device performance.
- Deployment: Converted models can be run via LiteRT-LM.
- Hardware Support: Currently supports CPU and GPU, with planned support for NPU.
- Containerization: When using the nightly package, you can use the
litert-lm-builderCLI tool to package your.tflitemodel and a tokenizer into a.litertlmcontainer.
Workflow for supporting new LLMs with Edge Generative API
mainTo support a new Large Language Model (LLM) using the LiteRT Torch Edge Generative API, follow this multi-step workflow:
- Model (re)authoring: Define the model architecture using
litert_torchtransformer building blocks and create ann.Modulewith aget_model_configfunction and adefine_and_runfunction. - Checkpoint mapping/loading: Map the original model's
state_dictto the new model's structure usingTensorNamestemplates andModelLoader. - Model verification: Compare the (re)authored model's output against the original reference implementation (e.g., using
verify.py). - Model conversion: Convert the PyTorch
nn.Moduleto a multi-signature TFLite flatbuffer using the LiteRT Torch conversion API. - Model quantization: Apply quantization (e.g., via PT2E) using recipes from
quant_recipes.pyduring the conversion process. - Evaluation & Deployment: Perform quality evaluation, benchmarking, and author the on-device inference pipeline.
- Model (re)authoring: Define the model architecture using
Re-author models using Edge Generative API layers
mainTo integrate LLMs into Android or iOS apps, you should re-author your existing PyTorch LLM using the library's provided building blocks (found in
layers/). These blocks support encoder-only, decoder-only, and encoder-decoder architectures.Refer to the
examples/directory for detailed guides on re-composing popular architectures such as:- Gemma
- TinyLlama
- Phi-2
Wrap models with non-standard interfaces
mainIf your PyTorch model does not follow the standard
forward(tensors) -> tensorspattern (e.g., it useskwargsor returns custom objects), you must provide atorch.nn.Modulewrapper. The wrapper'sforwardmethod should map the positional tensor arguments to the internal model's interface and return a tuple or list of tensors.class MyModelWrapper(torch.nn.Module): def __init__(self): super().__init__() self.m = MyModel() def forward(self, tensor1, tensor2): # Map positional args to internal kwargs and return tensors as a tuple custom_output_object = self.m(arg1=tensor1, arg2=tensor2) return custom_output_object.out_tensor1, custom_output_object.out_tensor2 # Pass the wrapper to convert edge_model = litert_torch.convert(MyModelWrapper().eval(), sample_inputs)Optimize performance via High-Level Function Boundaries (HLFB)
mainTo prevent the converter from breaking down critical operations (like Scaled Dot Product Attention - SDPA) into inefficient individual ops, the system uses High-Level Function Boundaries (HLFB).
By marking the inputs and outputs of a complex operation using
builder.mark_inputsandbuilder.mark_outputs, the operation is wrapped in a StableHLO composite op (e.g.,odml.scaled_dot_product_attention). The TF Lite converter then maps this directly to a highly optimized TF Lite custom op, which the on-device delegate (like XNNPack) can replace with specialized hardware kernels.Construct and convert decoder-only LLMs using LiteRT Torch Generative API
mainThe LiteRT Torch Generative API allows you to construct new PyTorch Large Language Models (LLMs) from scratch using transformer building blocks. Once constructed, these models can be converted to the TFLite format to enable efficient on-device inference. The library provides examples for a wide variety of popular decoder-only transformer architectures, including Gemma, Llama, Phi, and Qwen.Use ODML UNet 2D blocks for AutoEncoder and UNet models
mainThe
blocks_2d.pymodule provides common PyTorch building blocks designed for re-authoring UNet-based models, AutoEncoders, and text-to-image diffusion models.Each block is initialized using a corresponding configuration class defined in
model_config.py.Available blocks include:
ResidualBlock2D: A basic residual layer with two convolution layers and an optional time embedding layer.AttentionBlock2D: Self-attention layer for 2D tensors.CrossAttentionBlock2D: Cross-attention layer for 2D tensors, facilitating interaction between a latent tensor and a context tensor.FeedForwardBlock2D: A basic feed-forward layer used in transformer 2D blocks.TransformerBlock2D: A building block for text-to-image diffusion models, composed ofAttentionBlock2D,CrossAttentionBlock2D, andFeedForwardBlock2D.DownEncoderBlock2D: An encoder block for AutoEncoders and UNets, featuring an optional down-sampling layer.UpDecoderBlock2D: A decoder block for AutoEncoders and UNets, featuring an optional up-sampling layer.SkipUpDecoderBlock2D: A decoder block specifically for UNets that incorporates skip connections from the encoder.MidBlock2D: A middle block used in AutoEncoders and UNets.