Optimize ML Models for Mobile via Knowledge Distillation

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
Optimize ML Models for Mobile via Knowledge Distillation
Complex
~5 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

A mobile neural network must be lightweight yet accurate. Knowledge Distillation is a method that compresses a large model without critical quality loss. We have applied this approach on dozens of projects: from image classification to on-device NLP. The result — a model 10 times smaller with only a 1–2% accuracy drop. This approach is especially in demand in mobile ML, where every megabyte and millisecond count. Contact us — we will audit your model and propose a distillation plan.

Why Soft Labels Work Better

Standard training: correct class = 1.0, others = 0.0. Hard labels. A teacher on an image of a cat outputs: cat 0.85, lynx 0.08, tiger 0.04, dog 0.02 ... These "soft" labels carry information that a lynx is more similar to a cat than to an airplane. A student trained on such labels learns the structure of feature space, not just a binary classifier decision. This is the essence of the student-teacher paradigm.

import torch
import torch.nn.functional as F

def distillation_loss(student_logits, teacher_logits, true_labels, temperature=4.0, alpha=0.7):
    """
    alpha — weight of distillation vs hard label loss
    temperature — smooths teacher distribution
    """
    # Soft targets loss (KL divergence between student and teacher)
    soft_teacher = F.softmax(teacher_logits / temperature, dim=-1)
    soft_student = F.log_softmax(student_logits / temperature, dim=-1)
    distill_loss = F.kl_div(soft_student, soft_teacher, reduction='batchmean') * (temperature ** 2)

    # Hard label loss (standard cross-entropy)
    hard_loss = F.cross_entropy(student_logits, true_labels)

    return alpha * distill_loss + (1 - alpha) * hard_loss

temperature ** 2 — normalizing factor that compensates for gradient scale at high temperature. Without it, distill_loss and hard_loss are at different scales.

Choosing Student Architecture

The student must be smaller than the teacher, but not arbitrarily. Good base architectures for mobile:

  • MobileNetV3-Small — 2.5 MB, designed for mobile from scratch, depthwise separable convolutions
  • EfficientNet-Lite0/1 — good accuracy/speed balance
  • MobileViT-XXS — hybrid CNN+Transformer, 1.3 MB
  • DistilBERT (for NLP) — already distilled from BERT, 66 MB vs 440 MB

For object detection on mobile: student based on YOLOv8n (8 MB) distilled from YOLOv8l (87 MB).

Architecture Parameters Top-1 ImageNet (distillation) Size (FP32) Latency (iPhone 13)
MobileNetV3-Small 2.5M 71–72% 10 MB 15 ms
EfficientNet-Lite0 3.5M 74–75% 14 MB 20 ms
MobileViT-XXS 1.3M 69–70% 5.2 MB 18 ms
DistilBERT (NLP) 66M ~97% of BERT 264 MB 30–80 ms

How Distillation Methods Compare?

There are several distillation approaches, differing in complexity and outcome. Main ones: logit distillation (on outputs), intermediate layer distillation, and data-free distillation. Choice depends on data availability and accuracy requirements.

Method Student training Required data Complexity Typical accuracy drop
Logit distillation On teacher's soft labels Full dataset Low 1-2%
Feature (intermediate) distillation On outputs of intermediate layers Full dataset Medium 0.5-1%
Data-free distillation On synthetic data None High 2-5%

Distillation Steps

  1. Teacher preparation: fine-tune or quantize existing model, freeze weights.
  2. Student architecture selection: fit resource budget (RAM, CPU, latency).
  3. Hyperparameter tuning: temperature (usually 2-8), alpha (0.5-0.9), choice of layers for intermediate distillation.
  4. Student training: minimize combined loss, monitor validation accuracy.
  5. Conversion to Core ML/TFLite with int8 quantization for final size.
  6. Validation on real devices: check latency and accuracy.

Distillation Process: Example for Classification

# Assume: teacher — ResNet-50, student — MobileNetV3-Small
teacher = torchvision.models.resnet50(pretrained=True).eval()
student = torchvision.models.mobilenet_v3_small(pretrained=False)

# Freeze teacher
for param in teacher.parameters():
    param.requires_grad = False

optimizer = torch.optim.AdamW(student.parameters(), lr=1e-3, weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=100)

for epoch in range(100):
    student.train()
    for images, labels in train_loader:
        with torch.no_grad():
            teacher_logits = teacher(images)

        student_logits = student(images)

        loss = distillation_loss(student_logits, teacher_logits, labels,
                                  temperature=4.0, alpha=0.7)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    scheduler.step()
    val_acc = evaluate(student, val_loader)
    print(f"Epoch {epoch}: student_acc={val_acc:.4f}")

Typical results: MobileNetV3-Small trained normally — 67–68% top-1 on ImageNet. After distillation from ResNet-50 — 71–72%. Increase of 3–4% due to knowledge transfer.

How Does Intermediate Layer Distillation Work?

Distillation only on outputs (logits) is the basic version. A stronger version: add correspondence of intermediate feature maps.

# FitNets / PKT: student learns teacher's feature maps
class DistillationHook:
    """Hook to capture intermediate activations"""
    def __init__(self):
        self.output = None

    def __call__(self, module, input, output):
        self.output = output

teacher_hook = DistillationHook()
student_hook = DistillationHook()

# Register on corresponding layers
teacher.layer3.register_forward_hook(teacher_hook)
student.features[9].register_forward_hook(student_hook)  # Analogous layer

# In training loop add feature distillation loss
with torch.no_grad():
    teacher(images)
teacher_features = teacher_hook.output

student(images)  # with grad
student_features = student_hook.output

# If dimensions differ — need adapter (1x1 Conv)
if teacher_features.shape[1] != student_features.shape[1]:
    student_features = adapter_conv(student_features)  # adapter trained jointly

feature_loss = F.mse_loss(student_features, teacher_features.detach())

This approach requires alignment of feature map dimensions between teacher and student — via 1×1 convolutional adapters. The adapter adds a few parameters to the student but remains small.

How to Distill a Model if Original Data Is Unavailable?

Sometimes the original dataset is unavailable (IP restrictions, privacy). Data-free distillation — generate synthetic data that maximizes teacher activations:

# DAFL (Data-Free Learning): generator creates "samples" for distillation
generator = Generator(latent_dim=256, img_channels=3)
optimizer_G = torch.optim.Adam(generator.parameters(), lr=1e-4)

for step in range(1000):
    z = torch.randn(batch_size, 256)
    fake_images = generator(z)

    # Losses: maximize teacher confidence + minimize BatchNorm statistics mismatch
    teacher_out = teacher(fake_images)
    activation_loss = -teacher_out.max(dim=1)[0].mean()  # teacher should be confident

    # BN statistics matching
    bn_loss = compute_bn_statistics_loss(teacher, fake_images)

    total_loss = activation_loss + 0.1 * bn_loss
    optimizer_G.zero_grad()
    total_loss.backward()
    optimizer_G.step()

The quality of data-free distillation is lower than the full-data version, but sometimes it is the only option.

Distillation for NLP Tasks on Mobile

For mobile apps with NLP (sentiment classification, intent detection, summarization): distill from GPT-4 / Claude API responses into a small BERT/DistilBERT.

# Collect soft labels from teacher (GPT-4 API)
# For each training example request class probabilities
# Store as training labels for student
# Student — DistilBERT fine-tuned on these soft labels

DistilBERT (66 MB, ONNX int8 — 18 MB) runs on-device in 30–80 ms on iOS/Android. GPT-4 in the cloud — hundreds of ms, costs per request.

What's Included in Our Work

  • Resource budget analysis: RAM, CPU, GPU, power consumption
  • Student architecture selection based on your constraints
  • Teacher preparation (fine-tuning, quantization)
  • Distillation with hyperparameter tuning (temperature, alpha, intermediate layers)
  • Validation on test set and on real devices
  • Conversion to Core ML / TFLite with int8 quantization
  • Integration and support (updates for new OS versions)

Our team has 10+ years of experience in mobile development and ML. We guarantee the model will run stably on iOS 14+ and Android 10+. Get a free engineer consultation on your model. Order distillation — we'll prepare a preliminary estimate in 1 day.

Timeline Estimates

Basic logit distillation for a classification task — 2–4 weeks (GPU time plus hyperparameter tuning). Full distillation with intermediate layers, non-standard architectures, data augmentation — 5–10 weeks. Custom estimate upon request.

Further reading: Knowledge Distillation on Wikipedia, PyTorch tutorial.

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.