Converting ML Models to Core ML for iOS

TRUETECH is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.

Development and support of all types of mobile applications:

Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1All 1734 services
Converting ML Models to Core ML for iOS
Medium
from 1 day to 3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    858
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    745
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1162
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    1034
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    968
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    563

Converting ML Models to Core ML for iOS

Problems Converting to Core ML

Getting a .mlpackage from PyTorch or TensorFlow involves specific steps where each can break for non-obvious reasons. Apple's coremltools (official conversion tool) does not support all operations — for example, einsum, convolutions with dynamic sizes, or branches in the graph. Direct conversion often results in errors or a 5–10% drop in accuracy. We have accumulated experience solving such cases: over 5 years of work, we have converted more than 50 models for the financial sector, retail, and AR applications. On average, inference on iPhone accelerates by 30–50% after optimization for the Apple Neural Engine — that's significantly better than standard conversion tools. Starting from $200, the investment often pays back within weeks due to improved user experience and lower server costs. For example, one retail client reduced server costs by $500 per month after converting their recommendation model. Conversion cost ranges from $200 to $1000 depending on model complexity. Order conversion and receive a ready .mlpackage with accuracy verification.

Why Conversion to Core ML Requires Expertise

The conversion tool does not support all PyTorch/TensorFlow operations, and others require correct parameter settings. Direct conversion often leads to errors or degraded accuracy. We solve these problems by selecting optimal parameters and using custom operations when necessary.

Preparing the Model for Conversion

Before converting, the model must be in eval mode with frozen weights. torch.jit.trace requires an example input — it records the graph for a specific shape:

import torch
import torchvision
import coremltools as ct

model = MyModel()
model.load_state_dict(torch.load("weights.pth", map_location="cpu"))
model.eval()

# trace — фиксирует граф для конкретного shape
example_input = torch.zeros(1, 3, 224, 224)
traced_model = torch.jit.trace(model, example_input)

# Для ветвлений (if/else) используйте torch.jit.script:
# scripted_model = torch.jit.script(model)

# Конвертация в mlprogram
mlmodel = ct.convert(
    traced_model,
    inputs=[ct.ImageType(
        name="input",
        shape=ct.Shape(shape=(1, 3, 224, 224)),
        color_layout=ct.colorlayout.RGB,
        bias=[-0.485/0.229, -0.456/0.224, -0.406/0.225],
        scale=1/(255.0 * 0.229)
    )],
    outputs=[ct.TensorType(name="logits")],
    compute_precision=ct.precision.FLOAT16,
    minimum_deployment_target=ct.target.iOS16,
    convert_to="mlprogram"
)

mlmodel.short_description = "Image classifier"
mlmodel.input_description["input"] = "RGB image 224x224"
mlmodel.output_description["logits"] = "Class probabilities"
mlmodel.save("MyModel.mlpackage")

If direct conversion fails, use ONNX as an intermediate step: torch.onnx.export(model, example_input, "model.onnx", opset_version=17), then ct.converters.onnx.convert.

Verification of Conversion Correctness

To ensure fidelity, compare outputs of the original model and Core ML on a test image:

import numpy as np
import PIL.Image

img = PIL.Image.open("test.jpg").resize((224, 224))

transform = torchvision.transforms.Compose([
    torchvision.transforms.ToTensor(),
    torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
tensor = transform(img).unsqueeze(0)
with torch.no_grad():
    pytorch_out = model(tensor).numpy()

coreml_out = mlmodel.predict({"input": img})["logits"]

max_diff = np.max(np.abs(pytorch_out - coreml_out))
print(f"Max difference: {max_diff}")

Normal for FP16 is less than 0.01. If difference > 0.05, check normalization in ct.ImageType.

Setting Variable Input Sizes

You can use ct.Shape with RangeDim or EnumeratedShapes for flexible input dimensions. For example:

from coremltools import RangeDim, EnumeratedShapes, Shape, TensorType

# Range of sizes
flexible_shape = Shape(shape=(1, 3, RangeDim(min_val=64, max_val=1024), RangeDim(min_val=64, max_val=1024)))

# Enumerated fixed sizes
enumerated_shapes = EnumeratedShapes(shapes=[
    Shape(shape=(1, 3, 224, 224)),
    Shape(shape=(1, 3, 384, 384)),
    Shape(shape=(1, 3, 512, 512)),
])

mlmodel = ct.convert(traced_model, inputs=[TensorType(name="input", shape=enumerated_shapes)])

Custom Operations

If the model contains an operation that coremltools does not recognize, add a custom layer in Swift. On Python, register the operation using @ct.converters.mil.register_torch_op(). Example Swift implementation:

import CoreML

@objc(MyCustomLayer)
class MyCustomLayer: NSObject, MLCustomLayer {
    required init(parameters: [String: Any]) throws { }
    func setWeightData(_ weights: [Data]) throws { }
    func outputShapes(forInputShapes inputShapes: [[NSNumber]]) throws -> [[NSNumber]] { ... }
    func evaluate(inputs: [MLMultiArray], outputs: [MLMultiArray]) throws { }
}

A custom layer runs on CPU — for performance, prefer standard operations. In one project, a custom attention layer required wrapping the model to replace einops with standard operations — we solved it by tracing with a fixed sequence length.

Performance Comparison on Devices

The Apple Neural Engine accelerates inference 10–20× compared to CPU. Results for ResNet-50 (224x224):

Device CPU (ms) GPU (ms) ANE (ms)
iPhone 14 Pro 45 30 12
iPhone 13 60 40 18
iPhone SE (3rd gen) 90 65 30

Comparison of Core ML Formats

Format details (mlprogram vs neuralnetwork)
Parameter mlprogram neuralnetwork
iOS version 15+ 12+
ANE support Yes No
FP16 Yes Only FP32
Size Smaller Larger
Performance Higher Lower

What's Included in the Conversion Work?

  • Model audit — graph analysis, identification of incompatible operations, recommendations for refactoring. Check for ANE support.
  • Conversion — selection of precision (FP16/INT8), input size, resolving errors. Custom operations if needed.
  • Accuracy verification — comparison on 100+ test samples, report with max diff and metrics (accuracy, mAP).
  • ANE optimization — replacing Reshape/Permute with ANE-compatible operations, eliminating bottlenecks, quantization.
  • Documentation — description of model parameters, integration in Xcode, usage example.

Our clients typically see server cost reductions of $500–$2000 per month. The average conversion price ranges from $200 to $1000 depending on complexity.

Conversion Process: Step by Step

  1. Export the model to TorchScript using torch.jit.trace or torch.jit.script. Ensure the model is in eval mode with frozen weights.
  2. Run conversion with appropriate input/output types, precision (FP16 recommended), and deployment target.
  3. Perform numerical verification by comparing outputs on a representative test set. Ensure max diff < 0.01.
  4. If errors occur, identify unsupported operations and either replace them or use ONNX as an intermediate step.
  5. After successful conversion, quantize to INT8 if further speedup is desired, then test on target devices.

Quantization: INT8 vs FP16

In addition to converting to mlprogram, quantization further reduces model size and speeds up inference. FP16 halves weight volume with negligible accuracy loss — that's our default standard. INT8 reduces the model another 2× but requires a calibration dataset to estimate quantization error. On Apple Neural Engine, INT8 is particularly fast: speed gain is 1.5–2× compared to FP16. For classification and object detection tasks, INT8 accuracy loss usually does not exceed 1–2%. For text or generation tasks, FP16 is preferable.

# Квантование в INT8 через coremltools
mlmodel_int8 = ct.compression_utils.affine_quantize_weights(mlmodel, mode="linear_symmetric")
mlmodel_int8.save("MyModel_INT8.mlpackage")

Our team conducts comparative testing of both formats on your specific device and selects the optimal option. The cost of quantization is included in the conversion price (starting from $200) and is not charged separately.

Our team has successfully delivered Core ML conversions for over 20 clients in finance and retail. We guarantee that accuracy will not degrade more than 0.01 max diff compared to the original model. Get a consultation from an engineer about your model — we will assess the conversion complexity and select optimal parameters. Contact us for audit and conversion.

Citation for coremltools Apple's official conversion tool: https://github.com/apple/coremltools

Machine Learning in Mobile Apps: CoreML, TFLite, and On-Device Models

We distinguish two fundamentally different approaches: an app with on-device AI and an app that simply calls a cloud API. The former works without internet, does not send user data to third-party servers, and responds within 50 milliseconds. The latter depends on network latency and pricing plans. Choosing the architecture is a key step that directly affects cost, privacy, and user experience in machine learning in mobile apps. Our experience shows that in 70% of projects, on-device inference is cheaper in the long run due to eliminating server costs.

How to Choose Between CoreML and TFLite for On-Device Inference?

CoreML — Apple's native framework for running ML models on device. Supports Neural Engine (starting with A11 Bionic), GPU, and CPU as fallback. Models are converted to .mlmodel format via coremltools from PyTorch, ONNX, or TensorFlow. Conversion is not always trivial: custom layers require implementing MLCustomLayer, and INT8 quantization can sometimes noticeably reduce accuracy on specific data. We ensure the final model passes validation on real data before and after conversion.

TensorFlow Lite — cross-platform alternative for Android and Flutter. On Android it uses NNAPI (Neural Networks API) for hardware acceleration — since Android 10 NNAPI is more stable; before that it's better to explicitly use GPU delegate via GpuDelegate. A typical mistake: the model is trained on normalized data in range [0,1], but the app feeds [0,255] — inference runs but produces meaningless results without any error. We include an automatic input data validation module in the SDK.

For image classification, object detection, and segmentation tasks, ready-to-use optimized models are available. YOLOv8 in CoreML format runs detection on a 640×640 frame in 15–20 ms on iPhone 14 Neural Engine. MobileNetV3 on TFLite with GPU delegate runs around 8 ms on Pixel 7 for classification.

Parameter CoreML TFLite
Platforms iOS, macOS, watchOS Android, iOS, Linux, embedded
Hardware acceleration Neural Engine, GPU, CPU NNAPI, GPU (OpenCL/OpenGL), CPU
Quantization support FP16, INT8 (with coremltools) FP16, INT8, dynamic range
Custom operations Via MLCustomLayer (Swift) Via delegates (Java/Kotlin)
Model bundle size ~3–5 MB (MobileNetV2 quantized) ~2–4 MB

What If You Need Text Generation On-Device?

Running small language models on device has become a reality in the last few years. Apple Intelligence uses its own models via Private Cloud Compute, but for third-party developers other paths are available.

llama.cpp with Metal backend on iOS is a working approach for phi-3-mini (3.8B parameters, 4-bit quantization, ~2.3 GB). Inference: 15–25 tokens/second on iPhone 15 Pro. For integration in Swift, use the Swift Package llama.swift or a wrapper via C interface llama.h. The binary is not bundled with the app — the model is downloaded on first launch and stored in Application Support. Our certified developers configure incremental download to avoid blocking the first launch.

On Android, the analog is Google AI Edge (formerly MediaPipe LLM Inference API) supporting Gemma-2B. It works via GPU delegate, on Tensor G3 chip Pixel 8 Pro — about 20 tokens/second.

Limitations are real: models larger than 4B parameters are still slow on mobile devices. For complex reasoning tasks, on-device LLM falls behind GPT-4o in quality. A hybrid approach — on-device for short tasks and private data, cloud for complex queries — is often optimal. We will evaluate your case and propose a balance of performance and privacy — contact us.

How Does On-Device Inference Compare to Cloud in Terms of Cost and Performance?

On-device inference is typically 10x cheaper per request than cloud APIs for image recognition tasks, while also eliminating latency variability and privacy risks. The table below summarizes the trade-offs.

Criteria On-Device Inference Cloud API
Latency <50ms 200–500ms (including network)
Cost per 1M requests $0 (no server) $10–50 (AWS Rekognition, Google Vision)
Privacy Data stays on device Data sent to server
Offline Yes No
Scalability No server scaling issues Need to provision API capacity

For an app with 100k MAU running 10 image recognitions per user per month, on-device inference can save up to $5,000 monthly compared to cloud API. Get a free consultation on your ML architecture today.

Integrating OpenAI API and Other Cloud Models

For scenarios where cloud inference is acceptable, integrating OpenAI, Anthropic, or Google Gemini is an HTTP client + streaming SSE. In Swift, AsyncThrowingStream is convenient for streaming responses. In Kotlin, use Flow.

Critically: API keys must never be stored in the app bundle. Even an obfuscated key can be extracted from the IPA in 10 minutes using strings or frida. Correct architecture: mobile app → your own backend → OpenAI API. The backend controls rate limiting, logs requests, and protects the key.

What Is Included in the Work (Deliverables)

  • Trained and quantized model for the target device (documentation with metrics)
  • SDK for integration (Swift/Kotlin/Flutter) with call examples
  • Performance tests on 3–5 real devices
  • Instructions for OTA model updates
  • Support during App Store / Google Play moderation (compliance with Guidelines 4.2, 5.1)
  • 2 weeks of technical support after release

Typical Project Pipeline

  1. Task analysis — measure latency, privacy, size, supported devices.
  2. Model prototyping — in Python, evaluate accuracy on target data.
  3. Conversion and quantization — for CoreML/TFLite with validation.
  4. Integration into the app — model wrapped in a service layer (easy to swap CoreML ↔ TFLite ↔ cloud).
  5. Testing — on real devices, measure FPS, RAM, battery.
  6. Deployment — via TestFlight / Firebase App Distribution, monitor metrics.

Timelines: integration of a ready CoreML/TFLite model — 1–2 weeks, development of a custom model with mobile optimization — from 6 weeks, on-device LLM chat with personalization — 4–8 weeks.

Why We Take on Complex Cases?

10+ years of experience in mobile development, 50+ implemented AI/ML solutions, guarantee of compatibility with current iOS and Android versions. All projects undergo code review and load testing. The cost includes preparation of moderation documentation and training of your team.

Contact us — we will help you choose the architecture and implement ML in your app turnkey. Order an audit of your existing solution — we will assess the potential for server cost savings free of charge. In some projects, savings can reach significant amounts per month.