React Native ExecuTorch

repository·main·Indexed 23 days ago

https://github.com/software-mansion/react-native-executorch

A declarative framework for running on-device AI models (LLMs, Computer Vision, Speech) in React Native using ExecuTorch. It supports the New React Native architecture and provides specialized resource fetchers for Expo and bare React Native projects, as well as hooks like useLLM for chat completions and useBackgroundBlur for WebRTC applications.

Tokens
89.5K
Snippets
166
Records
330
Agent score
81%

What's inside react-native-executorch

  1. What is Out-of-the-Box Support?

    main
    Out-of-the-Box Support refers to models, architectures, or features that work immediately with React Native ExecuTorch. This means you can use them without custom compilation, manual kernel registration, or complex configuration. For example, standard Llama architectures have out-of-the-box support, allowing you to download a .pte file and run it instantly.
  2. Understand LLM generation: Prefill and Tokenization

    main

    When using Large Language Models (LLMs), the following terms describe the text processing lifecycle:

    • Prefill: The initial phase of text generation where the model processes the entire input prompt (context) at once. This is computationally intensive and its speed is often measured by Time to First Token (TTFT).
    • Token: The basic unit of text (word, part of a word, or character) that an LLM processes. Models have a Context Window limit, which is the maximum number of tokens they can hold in memory.
    • Tokenization: The process of converting raw text strings into numerical IDs (tokens).
    • TokenizerModule: A utility class in React Native ExecuTorch that handles encoding text into tensors and decoding output tensors back into readable text strings.
  3. Use the SpeechToTextModule for non-React contexts

    main

    The SpeechToTextModule provides a direct interface to speech-to-text (STT) capabilities. While the useSpeechToText hook is recommended for React components, use this module for full control over the model's lifecycle in non-React contexts or advanced use cases. You can perform one-shot transcription (for files/clips) or streaming transcription (for live microphone input).

    import { SpeechToTextModule, models } from 'react-native-executorch';
    
    // Initialize the model
    const model = await SpeechToTextModule.fromModelName(
      models.speech_to_text.whisper_tiny_en(),
      models.vad.fsmn_vad(),
      (progress) => {
        console.log(`Loading: ${progress * 100}%`);
      }
    );
    
    // 1. One-shot transcription
    const result = await model.transcribe(waveform);
    
    // 2. Live streaming
    model.streamInsert(audioChunk);
    const stream = model.stream({ useVAD: true });
    for await (const { committed, nonCommitted } of stream) {
      // Handle results
    }
  4. Perform promptable selection on segmented instances

    main

    Once you have obtained an array of SegmentedInstance objects via forward(), you can use selector functions to pick specific instances based on user interaction without re-running the model.

    Selector Types

    • Point Selection (selectByPoint): Finds the smallest instance whose mask covers the provided (x, y) coordinates. Ideal for tap-to-select.
    • Box Selection (selectByBox): Finds the instance with the highest IoU (Intersection over Union) with a provided bounding box { x1, y1, x2, y2 }. Ideal for drag-to-outline.
    • Text Selection (selectByText): Finds the instance with the highest cosine similarity between provided instanceEmbeddings and a textEmbedding. Ideal for search-by-description.

    Workflow

    1. Load model with useInstanceSegmentation.
    2. Run model.forward(image) once.
    3. Use a selector to pick the instance.
    4. Re-run the selector when the prompt/interaction changes (do not call forward again unless the image changes).
    import {
      models,
      useInstanceSegmentation,
      selectByPoint,
      selectByBox,
      selectByText,
    } from 'react-native-executorch';
    
    const model = useInstanceSegmentation({
      model: models.instance_segmentation.fastsam_x(),
    });
    
    try {
      const instances = await model.forward(imageUri);
    
      // Point: the smallest instance whose mask covers (x, y).
      const pointMatch = selectByPoint(instances, x, y);
      
      // Box: the instance with highest IoU with the prompt box.
      const boxMatch = selectByBox(instances, { x1, y1, x2, y2 });
    
      // Text: highest cosine similarity between text and per-instance image embeddings.
      const textMatch = selectByText(instances, instanceEmbeddings, textEmbedding);
    } catch (error) {
      console.error(error);
    }
  5. Manage StyleTransferModule memory

    main

    The StyleTransferModule is a standard JavaScript object managed by the garbage collector. However, if you need to release the memory occupied by the module immediately rather than waiting for garbage collection, call the delete() method on the module instance.

    Warning: Once delete() is called, you cannot use the forward() method on that instance again unless you reload the module.

  6. How Vision models and hooks work together

    main

    Vision tasks (classification, detection, segmentation, etc.) are implemented using specialized hooks. All models are selected via a typed models registry using the pattern models.<category>.<model>({ quant?, backend? }).

    Key Concepts:

    • Model Selection: Calling a model function with no arguments returns the platform default (CoreML on iOS / XNNPACK on Android). Passing a backend that the model doesn't support results in a compile-time error.
    • Input Formats: Every vision hook accepts image input as a remote URL (https://...), a local file URI (file://...), a base64 string, or a bundled asset via require('../assets/img.jpg'). Remote images are cached automatically.
    • Registry Pattern: Use the models object to access specific model architectures for each category.
  7. Understand the Forward Function and Inference

    main

    When working with models in React Native ExecuTorch, you will encounter these core concepts:

    • Forward Function: This is the primary method of a PyTorch module (typically forward()) that defines the computation logic. In ExecuTorch, this logic is exported and compiled. Running inference in React Native involves invoking this compiled function with new inputs.
    • Inference: The actual process of using a trained machine learning model to generate outputs or make predictions from input data.
  8. Critical audio rules for Speech and TTS

    main

    To avoid garbled audio or incorrect playback speeds, you must adhere to these sample rate and channel requirements:

    • Speech-to-text (STT) input: Must be 16 kHz mono. Mismatched sample rates will result in silently garbled transcriptions.
    • Voice Activity Detection (VAD) input: Must be 16 kHz mono.
    • Text-to-speech (TTS) output: The output is 24 kHz. You must create your playback AudioContext with { sampleRate: 24000 } to avoid 'chipmunked' or slow audio.
  9. Choose the right hook for your AI feature

    main

    React Native ExecuTorch provides specialized hooks for different AI tasks. Use the following decision guide to select the appropriate hook:

    Text & LLM

    • Chat / Text Generation: useLLM (supports plain chat, Vision-Language Models with LFM2_VL_*, tool calling, and structured JSON output).

    Computer Vision

    • Image Classification: useClassification (what is in the image).
    • Object Detection: useObjectDetection (bounding boxes).
    • Segmentation: useSemanticSegmentation (per-pixel class) or useInstanceSegmentation (per-instance).
    • Human Pose: usePoseEstimation (keypoints).
    • OCR: useOCR (horizontal) or useVerticalOCR (vertical/CJK).
    • Image Generation/Transformation: useStyleTransfer (artistic filters) or useTextToImage (Stable Diffusion).
    • Embeddings: useImageEmbeddings (CLIP vectors).

    Audio & Speech

    • Transcription: useSpeechToText (Whisper).
    • Synthesis: useTextToSpeech (Kokoro).
    • Voice Activity: useVAD (detecting speech segments).

    Text Utilities

    • Embeddings: useTextEmbeddings (sentence vectors).
    • Tokenization: useTokenizer (HuggingFace-compatible).
    • Privacy: usePrivacyFilter (PII redaction).

    Custom Models

    • Custom .pte files: useExecutorchModule (for models not covered by dedicated hooks).
  10. Understand Quantization and Tensors

    main

    These terms describe the data structures and optimization techniques used in the library:

    • Tensor: The fundamental multi-dimensional array (e.g., a matrix) used to hold model inputs, weights, and outputs. For example, an image might be a tensor with shape [3, 224, 224].
    • Quantization: A technique used to reduce model size and increase inference speed by converting weights and activations to lower-precision data types (e.g., 32-bit floating-point to 8-bit integers). This reduces RAM usage and saves battery life on mobile devices, typically with a negligible trade-off in accuracy.