Skip to main content

Overview

Off Grid’s iOS implementation uses Swift native modules bridged to React Native via Objective-C. The platform leverages Apple’s Neural Engine (ANE) for image generation, Metal GPU for LLM inference, and native iOS frameworks (PDFKit, URLSession) for document processing and downloads.

Native Modules

CoreMLDiffusionModule

Manages Stable Diffusion inference on iOS using Apple’s ml-stable-diffusion pipeline with Neural Engine acceleration. File: ios/CoreMLDiffusionModule.swift Architecture:
  • Uses Apple’s StableDiffusionPipeline (SD 1.5/2.1) or StableDiffusionXLPipeline (SDXL)
  • Both pipelines conform to StableDiffusionPipelineProtocol
  • Automatic SDXL detection via TextEncoder2.mlmodelc presence
  • Serial dispatch queue (ai.offgridmobile.coreml.diffusion) for thread safety
  • Mirrors Android LocalDreamModule interface for cross-platform abstraction
Pipeline Selection:
SDXL models contain TextEncoder2.mlmodelc (second text encoder), while SD 1.5/2.1 have only TextEncoder.mlmodelc. Model Loading:
Standard pipeline for SD 1.5 and 2.1 models. Uses single text encoder with last_hidden_state output.
Compute Configuration:
Core ML automatically dispatches ops to ANE (Neural Engine) or CPU based on op compatibility. Most SD ops (convolutions, matrix multiplies) run on ANE. Image Generation Flow:
Progress Callbacks: Pipeline invokes callback after each denoising step. Returning false cancels generation. Image Persistence:
Images saved to Documents/generated_images/ as PNG. Thread Safety:
Serial queue prevents concurrent pipeline access (Core ML pipelines are not thread-safe).

PDFExtractorModule

Extracts text from PDF files using Apple’s PDFKit framework. File: ios/OffgridMobile/PDFExtractor/PDFExtractorModule.swift Implementation:
PDFKit Advantages:
  • Native iOS framework (no third-party dependencies)
  • Handles encrypted/password-protected PDFs
  • Preserves text layout and reading order
  • Automatic page boundary detection
Character Limit: Extraction stops at maxChars (default 50,000) to prevent overwhelming the LLM context window.

Core ML Stable Diffusion Pipeline

Pipeline Architecture

Scheduler: DPM-Solver++

Apple’s pipeline uses DPM-Solver++ Multistep scheduler (default) for faster convergence:
  • 20 steps produces high-quality results (vs. 50+ steps for Euler)
  • Better detail preservation at low step counts
  • Supports guidance scale (CFG) for prompt adherence
Configuration:

Safety Checker: Disabled

Apple’s default pipeline includes NSFW safety checker. Off Grid disables it for:
  1. Reduced latency — No secondary Core ML model invocation
  2. User control — On-device generation is private; users decide content policy
  3. Model size — Safety checker adds ~200MB to model bundle
Disabled via reduceMemory: true (side effect: also reduces peak memory usage).

Model Variants

Size: ~1GB
Precision: 6-bit quantized weights
Performance: ~15-25s on A17 Pro/M-series (2x slower than fp16 due to dequantization)
Use case: Memory-constrained devices (iPhone 12, iPad Air 5)
Models:
  • SD 1.5 Palettized
  • SD 2.1 Palettized
  • SDXL iOS (~2GB, 4-bit mixed-bit palettization)
Model Source: All models from Apple’s official HuggingFace repos:
  • apple/coreml-stable-diffusion-v1-5
  • apple/coreml-stable-diffusion-2-1-base
  • apple/coreml-stable-diffusion-xl-base
Pre-compiled .mlmodelc bundles (Core ML compiled model format).

Hardware Acceleration

Neural Engine (ANE)

Apple’s dedicated AI accelerator, available on A11+ and M-series chips. Capabilities:
  • 16 TOPS (A17 Pro), 18 TOPS (A18 Pro), 38 TOPS (M4)
  • Optimized for convolutions, matrix multiplies, activations
  • Low power consumption (vs. GPU)
  • Automatic op dispatch via Core ML
Core ML Compute Units:
ANE Optimization: Core ML automatically converts fp16 ops to ANE’s native precision (8-bit for activations, 16-bit for weights). Palettized models dequantize on-the-fly.

Metal GPU (LLM Inference)

Llama.cpp uses Metal Performance Shaders (MPS) for GPU-accelerated LLM inference via llama.rn. Configuration:
  • User sets GPU layers (0-99) in model settings
  • Metal backend offloads transformer layers to GPU
  • Automatic fallback to CPU if Metal initialization fails
Performance:
  • A17 Pro / M-series: 25-50 tok/s with Metal
  • CPU-only: 10-20 tok/s (ARM NEON)
Memory Safety:
Metal buffer allocation can call abort() on low-RAM devices (≤4GB), killing the app before JavaScript catches the error. GPU layers forced to 0 on these devices. CLIP GPU Acceleration:
Same protection for CLIP warmup during vision model initialization.

Build Configuration

Xcode Project

Minimum Deployment Target: iOS 14.0 Required Frameworks:
  • CoreML.framework — Core ML inference engine
  • PDFKit.framework — PDF text extraction
  • Foundation.framework — File I/O, networking
  • UIKit.framework — Image encoding
Swift Package Dependencies:
Apple’s ml-stable-diffusion library provides StableDiffusionPipeline and StableDiffusionXLPipeline.

Bridging Headers

Objective-C Bridge Files:
  • ios/CoreMLDiffusionModule.m
  • ios/OffgridMobile/PDFExtractor/PDFExtractorModule.m
Expose Swift modules to React Native bridge:

Code Signing

Capabilities Required:
  • App Sandbox (optional for Mac Catalyst)
  • File Access (Documents folder)
Entitlements:

Performance Tuning

Image Generation

Step Count: Guidance Scale (CFG):
  • 1.0 — Ignores prompt, random images
  • 7.5 — Default, balanced prompt adherence
  • 15.0 — High adherence, may oversaturate
Resolution: SD 1.5/2.1 trained on 512×512. SDXL trained on 1024×1024 (downscaled to 768×768 for mobile).

Memory Management

Pipeline Unloading:
Core ML releases GPU/ANE memory when pipeline deallocates. Unload before switching models to prevent OOM. Reduce Memory Flag:
Enables:
  1. Pipelined UNet execution (processes latents in chunks)
  2. Safety checker disabled (saves ~200MB)
  3. Aggressive CoreML cache eviction
Trade-off: ~10% slower generation, but prevents crashes on 4GB devices.

Downloads (URLSession)

iOS uses react-native-fs (wraps URLSession) for background downloads instead of Android’s native DownloadManager. Background Transfer:
Downloads continue when app is backgrounded (iOS allows 30s of background execution, then suspends until download completes). Progress Tracking: URLSession delegate methods emit progress events:

Debugging

Core ML Logs

ANE Performance Profiling

Xcode Instruments:
  1. Profile → Metal System Trace
  2. Enable “Core ML” track
  3. Run image generation
  4. Inspect ANE vs. CPU vs. GPU op distribution
Expected ANE Utilization:
  • UNet: 95%+ on ANE (convolutions)
  • VAE Decoder: 80%+ on ANE
  • Text Encoder: 50-70% on ANE (some ops fall back to CPU)

References

  • Apple ml-stable-diffusion: https://github.com/apple/ml-stable-diffusion
  • Core ML Documentation: https://developer.apple.com/documentation/coreml
  • PDFKit Guide: https://developer.apple.com/documentation/pdfkit
  • Metal Performance Shaders: https://developer.apple.com/documentation/metalperformanceshaders
  • llama.cpp Metal: https://github.com/ggerganov/llama.cpp/blob/master/docs/backend/Metal.md