LiteRT Torch Documentation

repository·main·Indexed 21 days ago

https://github.com/google-ai-edge/litert-torch

A 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.

Tokens
21.7K
Snippets
59
Records
102
Agent score
77%

What's inside LiteRT Torch

  1. Overview of LiteRT Torch Generative API

    main
    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.
  2. Overview of LiteRT Torch Generative API

    main

    The 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:

    1. Start with a trained PyTorch LLM (e.g., from Hugging Face or Kaggle).
    2. Re-author the model using Edge Generative API layers to ensure mobile compatibility.
    3. Quantize the model to reduce size and improve performance.
    4. Verify implementation and quality using your evaluation pipeline.
    5. Convert the model to a LiteRT Flatbuffer.
    6. Deploy using either the LiteRT Runtime APIs (for maximum control) or the MediaPipe LLM Inference API (for ease of use).
  3. LiteRT LLM Calibration & Quantization Skill Overview

    main

    The litert-quantization-calib skill 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.
  4. What is the LiteRT Torch Generative API?

    main

    The 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-builder CLI tool to package your .tflite model and a tokenizer into a .litertlm container.
  5. Workflow for supporting new LLMs with Edge Generative API

    main

    To support a new Large Language Model (LLM) using the LiteRT Torch Edge Generative API, follow this multi-step workflow:

    1. Model (re)authoring: Define the model architecture using litert_torch transformer building blocks and create a nn.Module with a get_model_config function and a define_and_run function.
    2. Checkpoint mapping/loading: Map the original model's state_dict to the new model's structure using TensorNames templates and ModelLoader.
    3. Model verification: Compare the (re)authored model's output against the original reference implementation (e.g., using verify.py).
    4. Model conversion: Convert the PyTorch nn.Module to a multi-signature TFLite flatbuffer using the LiteRT Torch conversion API.
    5. Model quantization: Apply quantization (e.g., via PT2E) using recipes from quant_recipes.py during the conversion process.
    6. Evaluation & Deployment: Perform quality evaluation, benchmarking, and author the on-device inference pipeline.
  6. Re-author models using Edge Generative API layers

    main

    To 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
  7. Wrap models with non-standard interfaces

    main

    If your PyTorch model does not follow the standard forward(tensors) -> tensors pattern (e.g., it uses kwargs or returns custom objects), you must provide a torch.nn.Module wrapper. The wrapper's forward method 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)
  8. Optimize performance via High-Level Function Boundaries (HLFB)

    main

    To 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_inputs and builder.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.

  9. Construct and convert decoder-only LLMs using LiteRT Torch Generative API

    main
    The 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.
  10. Use ODML UNet 2D blocks for AutoEncoder and UNet models

    main

    The blocks_2d.py module 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 of AttentionBlock2D, CrossAttentionBlock2D, and FeedForwardBlock2D.
    • 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.