Fine-Tuning Small Models for Better On-Device Agent Performance
This article explores how to build practical on-device AI Agents under mobile constraints. It compares system-level models with app-bundled small language models, explains a prompt-driven skill-loading architecture, and outlines a narrow-and-deep fine-tuning strategy for function calling, text polishing, intent classification, and information extraction. It also covers synthetic data generation, offline speech transcription pipelines, resource management, validation, and production-readiness considerations.
1. Why Run an Agent On Device?
An Agent is an AI system that can understand user intent, select tools, and execute multi-step operations. In the traditional approach, these capabilities are handled by a large cloud-hosted model. However, mobile applications face several practical constraints:
- Network latency can make interactions feel sluggish.
- Offline scenarios cannot depend on cloud services.
- Frequent requests increase service costs.
- Users may be concerned about sending personal data off the device.
The main challenge of on-device deployment is limited resources. Phones have finite memory, compute capacity, and storage, while application package sizes must also remain manageable. As a result, the goal of an on-device Agent is not to use the largest possible model, but to make a model reliably complete specific tasks within a restricted resource budget.
2. Two Deployment Paths: System-Level and In-App Models
Most mobile on-device AI solutions follow one of two deployment paths.
2.1 System-Level Models
An operating system may include an optimized small language model that it centrally maintains and schedules. Applications can call this capability without bundling model files themselves.
Its main advantages include:
- Smaller application packages, with no additional download or storage burden;
- Centralized model updates and optimization, with system-level memory and power management;
- Low integration cost, making it suitable for general tasks such as text rewriting, summarization, and simple classification.
The limitation is reduced customization. Developers cannot change the model’s fundamental behavior, and performance may vary across devices and operating system versions.
2.2 In-App Small Models
Developers can distribute a small language model, or tiny language model (TLM), together with the application. These models typically contain between one hundred million and several hundred million parameters and can be trained for a specific business scenario.
Their advantages include:
- Strong control over model behavior, output formats, and update schedules;
- Consistent behavior across platforms without depending on a particular operating system version;
- More opportunities to optimize the model using domain-specific data.
The trade-offs are larger application packages, model updates that may require a new release or separate download, and additional memory usage.
2.3 Choosing Between the Two
| Evaluation Dimension | System-Level Model | In-App Small Model |
|---|---|---|
| Task type | General text processing | Fixed-format output or specialized tasks |
| Customization needs | Low | High |
| Platform coverage | Differences are acceptable | A consistent experience is required |
| Package size sensitivity | High | An additional download is acceptable |
| Update frequency | Managed with the operating system | Controlled by the development team |
In practice, the two approaches can be combined. For example, general text polishing can use a system-level capability, while function calls that must strictly follow a business protocol can be handled by an in-app model.
3. Prompt-Driven Skill Loading
To perform concrete actions, an Agent must call tools. An on-device system should not load every capability at startup, because doing so can slow startup time and consume substantial memory. A better approach is to load skills on demand: the model first determines what capability the user needs, and the application then loads the corresponding plugin dynamically.
The overall process has four steps:
- Organize the names, purposes, and parameter descriptions of available skills into a structured list.
- Use a prompt to ask the model to output the skill name and parameters required for the user’s request.
- Validate the output format, confirm that the skill exists, and verify that the parameters are valid.
- Dynamically load and execute the plugin, then return the result to the user.
The following example illustrates the structure. It is not an interface from a specific framework:
// Example structure: skill registry and on-demand loadingconst skillRegistry = {map: {description: "Find places and provide navigation routes",params: { destination: "string" },load: () => import("./skills/map.js"),},restaurantRoulette: {description: "Recommend a restaurant at random",params: { area: "string" },load: () => import("./skills/restaurant.js"),},};// Add the skill list to the prompt and require structured outputfunction buildPrompt(userInput) {const skillList = Object.entries(skillRegistry).map(([name, s]) => `${name}: ${s.description}`).join("\n");return `Available skills:\n${skillList}\nUser input: ${userInput}\nReturn JSON: {"skill": "...", "args": {...}}`;}// Validate model output before executing a callasync function runSkill(modelOutput) {const call = JSON.parse(modelOutput);const entry = skillRegistry[call.skill];if (!entry) throw new Error("Unknown skill");const mod = await entry.load();return mod.execute(call.args);}
Two points are especially important. First, skill descriptions must be clear enough for the model to make accurate decisions. Second, model output must never be executed directly. It must first be parsed and validated. For an on-device Agent, this validation layer is a major part of the system’s safety boundary.
4. Small Models Need a Narrow-and-Deep Fine-Tuning Strategy
Parameter count is an important factor in determining a model’s capability. When a model is reduced to roughly 100–200 million parameters, its general-purpose abilities can decline significantly. Instruction following becomes less reliable, long-context processing becomes unstable, and the model may fail to follow required output formats. Using such a model for open-ended conversation is usually impractical.
A more effective strategy is to go “narrow and deep”: limit the model to one or two frequently used tasks, then train it extensively with task-specific data. Common target tasks include function calling, text polishing, intent classification, and information extraction.
Building Synthetic Data
Real user data is often insufficient and may contain sensitive information, so synthetic data is commonly used in practice. One possible workflow is:
- Define the task specification: Clearly describe the input format, output structure, and error-handling rules.
- Design sample templates: Cover different phrasings, colloquial expressions, omitted information, and ambiguous sentences.
- Generate samples with a larger model: Ask a larger model to produce user-input and standard-output pairs based on the templates.
- Clean and deduplicate: Remove invalid formats, duplicates, and obviously unreasonable samples.
- Perform manual spot checks: Review a proportion of samples for important tasks to confirm label accuracy.
- Train and evaluate: Use an independent test set to measure performance and prevent overlap with the training data.
An example sample is shown below:
{"input": "Find highly rated hot pot restaurants near me","output": {"skill": "restaurantRoulette", "args": {"area": "nearby", "cuisine": "hot pot"}}}
Diversity is the key consideration in sample design. The same intent should be represented through colloquial language, abbreviations, typos, and information omitted across multiple turns. Otherwise, the model may perform well on curated examples but fail in real-world interactions.
5. Improving Function-Calling Accuracy Through Fine-Tuning
Function calling is one of the most important capabilities of an on-device Agent. The model must output the correct function name and parameters. An error in any field can prevent the tool from executing.
In one App Intents-related experiment, a prompt-only approach achieved a function-calling success rate of just 46%. After the team fine-tuned a small model using a synthetic dataset generated by a larger model, the success rate exceeded 90% on 80% of the tested functions.
This result came from a specific experiment. The number and complexity of the tested functions, as well as the evaluation criteria, directly affect the outcome. It should therefore be reassessed in the context of each application rather than applied as a universal benchmark.
The result highlights two points:
- Fine-tuning for a narrow task can provide much greater gains than prompt optimization alone.
- The upper performance limit of a small model depends heavily on the quality and coverage of its training data.
6. Offline Transcription: Using Multiple Models to Address On-Device Constraints
Speech-to-text is a common mobile requirement. A complete transcription experience generally involves two stages:
- Automatic speech recognition (ASR): Convert audio into raw text.
- Text polishing: Remove filler words, correct punctuation, and apply specialized terms from a personal dictionary.
In practice, both stages can be handled by small models with several hundred million parameters. The entire pipeline can run offline on the device, without a network connection or audio upload.
The chained architecture can be represented as follows:
// Example structure: offline transcription pipelineasync function transcribe(audioBuffer, personalDict) {const rawText = await asrEngine.recognize(audioBuffer); // Speech to textconst polished = await polishEngine.polish(rawText, { // Remove fillers and apply dictionarydictionary: personalDict,});return polished;}
Chaining multiple models introduces three engineering challenges:
- Accumulated latency: The models run sequentially, so total processing time is the sum of both stages. Segmented streaming output can help users see initial results earlier.
- Error propagation: Recognition errors may be amplified by the polishing stage. A confidence-based decision layer can be added between the two stages.
- Peak memory usage: The two models should not necessarily remain resident in memory at the same time. They can be loaded and released as needed.
7. Production Readiness Checklist
Before deploying an on-device Agent to production, verify the following:
- Task boundaries: Each small model should handle only one or two high-frequency tasks. Requests outside its scope should be routed to fallback logic.
- Output validation: All model outputs must pass format and parameter validation before entering the execution stage.
- Resource monitoring: Track cold-start time, per-inference latency, and peak memory usage, and test on lower-end devices.
- Fallback behavior: If model loading fails or device resources are insufficient, fall back to rule-based methods or prompt the user to complete the operation manually.
- Data compliance: Synthetic data and training samples must not contain real user privacy data.
- Version management: Keep model versions synchronized with skill definitions to prevent incorrect calls caused by pairing a new model with outdated skill descriptions.
8. Conclusion
A practical path for building on-device Agents can be summarized in three points.
First, choose between system-level models and in-app small models based on customization requirements and platform constraints. Second, use on-demand skill loading and output validation to control the Agent’s functional boundaries and execution safety. Third, fine-tune small models with a narrow-and-deep strategy, using high-quality synthetic data to improve success rates on specific tasks.
This approach does not depend solely on model size and is better suited to mobile devices with limited compute, memory, and storage resources.
