CONTENTS
Open Models, Fine-Tuning, and On-Device AI
So far we’ve treated models as APIs. This chapter goes one layer down: running models yourself, adapting them with fine-tuning, and putting them on phones. That last one is a natural specialty for a mobile engineer, and it remains comparatively under-served.
10.1 Open-weights models
“Open-weights” models publish their trained parameters so you can download, run, and modify them. (They’re not always “open source” in the strict sense; training data and code are often not released, and licenses vary. Read the license.)
Why use them:
- Data control: nothing leaves your infrastructure (important for regulated industries).
- Customization: full fine-tuning, not just API-level adaptation.
- Cost at scale: for high, steady volume on a narrow task, a self-hosted small model can be far cheaper.
- Offline / on-device: the only option for running locally.
- Research: you can inspect activations, do interpretability work, and modify architectures.
Why not: you own serving, scaling, GPU costs, security patching, and upgrades. The best closed frontier models generally lead on the hardest reasoning and agentic tasks, though open models have stayed competitive within months on many benchmarks.
The Hugging Face ecosystem is the hub: model repositories, transformers (load and run almost any model), datasets, peft (parameter-efficient fine-tuning), trl (training with SFT, DPO, and RL), and model cards that document capabilities and limitations.
10.2 Running models locally
# The easiest start: Ollama
ollama run qwen3:8b # model names change; browse the library for current ones
# OpenAI-compatible local endpoint at http://localhost:11434/v1
Other tools: LM Studio (GUI), llama.cpp (the C++ engine underneath much of the local ecosystem; runs nearly anywhere), MLX (Apple’s array framework, excellent on Apple Silicon), and vLLM or SGLang for high-throughput server deployments on GPUs.
What fits where (rough rules): memory needed is approximately parameters × bytes per parameter, plus room for the KV cache.
| Model size | FP16 (2 bytes) | 4-bit quantized (~0.5–0.6 bytes) | Runs on |
|---|---|---|---|
| 1–3B | 2–6 GB | ~1–2 GB | Phones, any laptop |
| 7–8B | ~16 GB | ~4–5 GB | Laptops, high-end phones (tight) |
| 30B-class | ~60 GB | ~17–20 GB | 32 GB+ Macs, a single big GPU |
| 70B-class | ~140 GB | ~40 GB | 64 GB+ Macs, multi-GPU |
10.3 Quantization: making models small
Quantization stores weights at lower precision (8-bit, 4-bit, even lower) instead of 16-bit floats. Fewer bits mean less memory and faster inference (LLM decoding is usually memory-bandwidth-bound: speed is limited by how fast weights stream from memory, so smaller weights stream faster).
Core concepts:
- Weight-only vs. weight + activation quantization. Weight-only (e.g., 4-bit weights, 16-bit compute) is common for on-device LLMs.
- Group-wise quantization: weights are split into small groups, each with its own scale factor, to preserve accuracy.
- Post-training quantization (PTQ) methods like GPTQ and AWQ quantize a finished model, using calibration data to minimize error. Quantization-aware training (QAT) simulates quantization during training for better quality at low bit-widths.
- Formats: GGUF (llama.cpp ecosystem), MLX formats, Core ML packages, ExecuTorch
.ptefiles, and others.
Rule of thumb: 8-bit is usually nearly lossless, 4-bit is the common sweet spot with modest quality loss, and below 4 bits quality degrades faster (task-dependent). Always eval the quantized model on your task. Quantization damage is uneven: it can hurt reasoning, multilingual, or long-context performance more than benchmarks suggest.
10.4 Fine-tuning: when and how
When to fine-tune
Fine-tuning is often reached for too early. Try in this order:
- Better prompting and context. (Fixes most problems.)
- Retrieval for knowledge problems.
- A better or bigger model.
- Fine-tuning, when you have a clear, eval-measured gap that the above can’t close.
Good reasons to fine-tune:
- Consistent format or style across very high volume, where long prompts are expensive.
- Distillation: make a small, fast, cheap model do what a big model does on a narrow task. This is the most common high-value use. Generate thousands of high-quality outputs with a frontier model, filter them with your evals, and train a small model on them.
- Domain adaptation for specialized language (medical, legal, internal jargon).
- On-device deployment: small models need fine-tuning to be good at your specific task.
- Behaviors that are hard to prompt reliably, with a reward signal you can define (RL fine-tuning).
Bad reasons: “teaching it our documentation” (use retrieval) or “it got 2 of 10 questions wrong” (that’s not enough data to know anything).
Types of fine-tuning
- Full fine-tuning: update all weights. Expensive, needs lots of GPU memory.
- LoRA (Low-Rank Adaptation): freeze the original weights and train small low-rank matrices that are added to them. Instead of updating a 4096×4096 weight matrix (16.7M parameters), you train (4096×16) and (16×4096), about 131k parameters, and use . This works because the change needed for fine-tuning tends to be low-rank: a small number of directions in weight space. Result: under 1% of parameters trained, much less memory, and you can swap different LoRA adapters on one base model at runtime.
- QLoRA: LoRA on a 4-bit quantized base model. Fine-tune 7–8B models on a single consumer GPU.
- Preference tuning (DPO etc.): train on “chosen vs. rejected” pairs to shift style and behavior.
- RL fine-tuning: optimize against a reward function or grader (e.g., GRPO-style methods popularized by open reasoning models). Powerful for tasks with verifiable outcomes, but trickier to get right.
The fine-tuning workflow
1. Define the task and build an eval set FIRST (Chapter 8)
2. Baseline: how do prompted models (big and small) perform?
3. Collect / generate training data (hundreds to tens of thousands of examples)
- quality >> quantity; deduplicate; filter with evals; NEVER include eval examples
4. Train (LoRA/QLoRA via Hugging Face TRL, Unsloth, Axolotl, or a provider's fine-tuning API)
5. Evaluate on the held-out eval set; check for regressions on general ability
6. Iterate on data (it's almost always the data)
7. Deploy (merge adapter or serve with adapter), keep monitoring
The key lesson every practitioner learns: fine-tuning is mostly a data problem. Model and hyperparameter choices matter far less than the quality, diversity, and correctness of the training examples.
10.5 On-device AI: the mobile engineer’s specialty
On-device inference runs models directly on phones, which gives:
- Privacy: data never leaves the device. A huge selling point for health, journaling, messaging, and photos.
- Latency: no network round trip; works offline.
- Cost: zero marginal inference cost per user.
- Constraints: limited memory (the OS kills apps that use too much), thermal throttling, battery drain, app-size limits, and a huge spread of device capabilities.
The platform landscape (check current docs; this area moves quickly)
Apple:
- Core ML: Apple’s on-device inference framework, which uses CPU, GPU, and the Neural Engine. Convert models with
coremltools. - Apple Foundation Models framework: Apple exposed its on-device foundation model to developers (announced at WWDC 2025), with Swift APIs for generation, guided (structured) generation, and tool calling, at no inference cost on supported devices.
- MLX / MLX Swift: efficient for running and fine-tuning open models on Apple Silicon.
Android / Google:
- Gemini Nano via AICore / ML Kit GenAI APIs: system-provided on-device model on supported devices.
- LiteRT (formerly TensorFlow Lite) and MediaPipe LLM Inference for running models on-device.
Cross-platform:
- ExecuTorch: PyTorch’s on-device runtime (iOS, Android, embedded), with delegates for Core ML, Qualcomm, MediaTek, Vulkan, and others. Meta uses it in production.
- llama.cpp: runs GGUF models nearly everywhere; there are React Native bindings (e.g.,
llama.rn). - ONNX Runtime Mobile.
- React Native libraries wrapping these runtimes (for example, Software Mansion’s
react-native-executorch). Integrating them well requires exactly your skills: JSI / Turbo Modules, threading, memory management, and native build tooling.
On-device engineering concerns
- Model delivery: don’t bundle a 2 GB model in your app binary. Download it on demand (with resumable downloads, integrity checks, and storage-pressure handling), or use OS-provided models where available.
- Memory: load lazily, unload under memory pressure, and pick quantization levels per device tier.
- Threading: never run inference on the JS or UI thread. Stream tokens back across the bridge efficiently.
- Device capability detection: route to on-device on capable devices, to cloud on others (with user consent where privacy expectations differ).
- Hybrid architectures: a small on-device model handles fast, private, simple tasks (classification, smart replies, summarizing short text, intent routing) and escalates to the cloud for hard ones.
- Evaluate per device tier: quality, tokens per second, battery, and thermals on real low-end devices, not just your flagship test phone.
Career angle: few AI engineers deeply understand mobile constraints, and few mobile engineers deeply understand models. The intersection, on-device and hybrid AI for mobile, is a strong niche for you.
10.6 Serving models at scale (the inference engineering frontier)
For awareness, especially if systems work interests you, the core ideas of high-performance LLM serving:
- Continuous batching: dynamically add and remove requests from the GPU batch at each decode step instead of waiting for a whole batch to finish.
- PagedAttention (vLLM’s innovation): manage the KV cache in fixed-size pages like OS virtual memory, which cuts fragmentation and lets more requests share GPU memory.
- Prefix caching: share KV cache across requests with common prefixes.
- Speculative decoding: a small “draft” model proposes several tokens; the big model verifies them in one parallel pass. Same output distribution, faster.
- Tensor and pipeline parallelism: split a model across multiple GPUs.
- Disaggregated prefill/decode: run compute-heavy prefill and memory-bound decode on separate hardware pools.
- Kernels: FlashAttention and similar fused GPU kernels that restructure attention to minimize slow memory reads and writes.
This is the domain of C++, CUDA, Triton (the GPU kernel language), and Rust, which matters if your interests lean toward systems. The concept underneath almost all of it: LLM inference is bottlenecked by memory bandwidth and memory capacity, not raw arithmetic, so most optimizations are about moving fewer bytes.
Key takeaways
- Open-weights models trade operational burden for control, privacy, customization, and potential cost savings.
- Quantization shrinks models (4-bit is the common sweet spot) because inference is memory-bandwidth-bound. Always eval after quantizing.
- Fine-tune last, not first. It’s for behavior, format, distillation, and on-device specialization, not knowledge. It is mostly a data problem.
- LoRA works because fine-tuning updates are low-rank; QLoRA puts it on consumer hardware.
- On-device AI (Core ML, Apple’s Foundation Models, Gemini Nano, ExecuTorch, llama.cpp) is a strong niche at the intersection of mobile and AI expertise.
- Inference engineering is about memory: batching, paging, caching, speculation, and fused kernels.
Exercises
- Run an 8B-class model locally with Ollama and point your Chapter 4 CLI at its OpenAI-compatible endpoint. Compare quality and speed with a cloud model on 20 prompts.
- Run the same model at 8-bit and 4-bit. Run a small eval (30 cases) on each. Measure the quality and speed differences.
- Distillation project: pick a narrow task (e.g., classifying app reviews into 8 categories). Label 2,000 examples with a frontier model, filter with your eval checks, then QLoRA fine-tune a 1–3B model (Unsloth notebooks make this accessible on a free or cheap GPU). Compare accuracy and cost per 1,000 calls.
- Build a React Native demo that runs a small model on-device (via
react-native-executorchorllama.rn) with streaming tokens, a cancel button, and memory-pressure handling. Profile it on the oldest device you can find.