Self-Hosting a 27B Distilled Model to Replace Paid APIs: A Complete Guide
This guide walks through replacing paid LLM APIs with a self-hosted 27B distilled model. It covers why local deployment makes sense for high-frequency, long-running, or data-sensitive workloads, how to choose a model while avoiding licensing risks, how to estimate VRAM and memory needs, how to use layer offloading when GPU memory is limited, how to connect the model to coding tools through an OpenAI-compatible interface, and how to benchmark results and make a cost decision. You'll find practical capacity tables, a working Modelfile example, tuning steps for GPU layer offload, and a troubleshooting reference.
1. Introduction: Why Replace Paid APIs with a Local Model
In scenarios like AI coding assistants, code review, and documentation generation, LLM-powered applications are shifting from “occasional calls” to “always on.” Agent-style tools call the model repeatedly within a single task: reading files, generating code, running commands, checking results, and iterating on fixes. One complex task can involve dozens of model calls, each carrying a large context.
This usage pattern creates three real pressures:
- Costs grow with usage intensity: Mainstream cloud LLM services typically bill input and output tokens separately. The longer the context and the more frequent the calls, the faster costs rise, making it hard to set a predictable monthly cap the way you can with local deployment.
- Data egress and compliance risk: Code, internal documents, and logs may contain sensitive information, and uploading them to external services requires a data security review.
- Limited control: Rate limits, network fluctuations, and server-side version updates can all affect the consistency and stability of results.
If you move these capabilities on-premises, inference runs on your own hardware, the marginal cost per call approaches zero, data never leaves your internal network, and behavior is more controllable.
Local deployment isn’t right for everyone. If your call frequency is low, you have no restrictions on data egress, and latency requirements aren’t strict, sticking with a mature API is usually less hassle. Self-hosting mainly fits high-frequency, long-running, data-sensitive, or customization-heavy scenarios.
That said, “local deployment” doesn’t mean “you must buy a top-tier GPU.” Take a recently released 27B-class (roughly 27 billion parameter) distilled instruction model as an example. These models use a general-purpose open-source model as the base and are distilled using reasoning traces and tool-calling data generated by a stronger teacher model with good reasoning ability, performing well in structured reasoning and function calling. Its quantized weights fit consumer GPUs with 24GB of VRAM, and smaller devices can run it at an acceptable generation speed after reasonable tuning—enough for everyday coding-assistance tasks.
Using this model as an example, this article explains in full:
- How to choose a model and avoid licensing risks;
- How to estimate VRAM and memory requirements;
- How to do layer offloading when VRAM is insufficient;
- How to connect to coding tools through a compatible interface;
- How to benchmark results and make a cost decision.
Note: The commands, configuration files, and parameters here are illustrative. Command syntax, parameter names, and default values may differ across versions and tools, so always refer to the official documentation of the tool you use.
2. Model Selection: What a Distilled Model Is and How to Choose One Safely
2.1 The Core Value of Distilled Models
The basic idea of knowledge distillation is to have a smaller “student model” learn the output behavior of a larger or more capable “teacher model.” Take distilling from dialogue data as an example: when the teacher model answers a question, it fully presents its analysis process, step-by-step conclusions, and—when external tools need to be called—the call intent and how arguments are structured. By learning from this data, the student model acquires similar organizational patterns.
In practice, distilled models usually have three characteristics:
- Clearer output structure: They tend to analyze first and then give conclusions, making it easier to stay consistent throughout long tasks;
- More reliable tool calling: They generate function names and arguments in the agreed format, reducing parsing failures;
- Lower resource overhead: They provide nearly usable capability with far less VRAM and compute than the teacher model.
For exactly these reasons, such models are well suited to run locally as the inference backend for tools like coding assistants and command-line agents.
2.2 Four Things to Verify When Choosing a Model
- Parameter size and model architecture: The parameter count sets the lower bound on weight size, while the number of layers, attention heads, and maximum context length determine runtime overhead. Public model cards usually provide this information, so read them carefully before deploying.
Quantization format and quantization level: Local inference generally uses a common quantization format (such as gguf) and uses a “quantization level” to indicate the trade-off between precision and size. Common levels include:
- 8-bit: smallest precision loss, but roughly half the size of full precision;
- 5-bit/6-bit: a balance between size and quality;
- 4-bit: smallest size, suitable for VRAM-limited scenarios.
The lower the quantization level, the more noticeable the drop in capability on high-precision tasks like code generation and mathematical reasoning, so choose based on benchmark results.
- Context length: Agent scenarios need to fit the system prompt, tool definitions, multi-turn dialogue, and file contents simultaneously, so they demand a large context window. Confirm the context length the base model was trained with, and whether the quantized version fully preserves this capability.
License and terms of use: This is the most easily overlooked item, yet the highest risk. Verify each of the following:
- The open-source license of the base model;
- The publication license for the distilled data and weights;
- Whether the source of the distilled data is compliant. If the distilled data comes from the output of some commercial model, confirm that its terms of service permit using that output to train other models and redistribute them.
Do not use models with licensing doubts in enterprise production or commercial products.
- Tool calling and templates: The model’s instruction-following format (the prompt template) must be compatible with your runtime environment; otherwise tool calling and multi-turn dialogue will frequently fail.
3. Capacity Planning: First Determine “Will It Fit?”
Before deploying, do the math. A quantized 27B model at the 4-bit level has weights of about 15GB, and with the overhead of the inference runtime, a full load needs roughly 24GB of VRAM—a single 24GB GPU can basically cover it, with room left for longer contexts.
But VRAM is only one constraint. Another often-overlooked constraint is system memory: when VRAM is insufficient, the weight layers not offloaded to the GPU can only reside in system memory. System memory capacity should be at least larger than the weight size, and it’s advisable to reserve some headroom for the operating system and other processes.
On this basis, use a simple decision method to determine a workable plan:
| Hardware | Recommended Approach | Expected Performance |
|---|---|---|
| VRAM ≥ 24GB | Full load, standard context length | Smooth, high generation speed |
| VRAM ~16GB | Layer offloading, or below-4-bit quantization + shorter context | Usable, be cautious with long contexts |
| VRAM ~12GB | Offload about 2/3 of the layers, moderately tighten context | Usable, speed roughly half of full load |
| VRAM < 8GB | A smaller model, or a smaller quantization level | Reassess model selection |
The following table uses a 4-bit quantized 27B model as an example to give configuration references across VRAM tiers (specific numbers vary by model architecture, quantization level, and version, and must be measured in practice):
| VRAM | Configuration | Generation Speed (Reference) |
|---|---|---|
| 24GB | Full load, context around 32K | Tens of tokens/s |
| 16GB | Load about 20–24 layers, context 8K–16K | About 15–25 tokens/s |
| 12GB | Load about 18–20 layers, context 4K–8K | About 10–20 tokens/s |
| 8GB | Load about 12–14 layers, context 2K–4K | Single digits to teens of tokens/s |
Note: The above are empirical reference values. Actual performance is affected by CPU memory bandwidth, quantization level, context length, and the inference backend implementation, so always rely on your own measurements.
This table shows a key conclusion: the cost of insufficient VRAM is speed, not “unusable.” As long as you accept a drop in generation speed, consumer GPUs can also run 27B-class models.
4. Layer Offloading: The Core Technique When VRAM Is Insufficient
4.1 How It Works
Modern LLM inference services generally use a “partial layer offloading” mechanism. A Transformer model is built by stacking a number of layers, each containing attention and a feed-forward network. During inference you can specify that some layers reside in VRAM while the rest stay in memory, moving them in as needed during layer-by-layer computation.
- Layers in VRAM are computed by the GPU for matrix operations, which is fast;
- Layers in memory are computed with the CPU’s help, or moved to VRAM before computation, which is slower.
Therefore, the more layers loaded onto the GPU, the faster the speed. This is also the key to “getting a 12GB VRAM setup running first.”
4.2 Steps
Step 1: Pull the model.
Download the 4-bit quantized weight file from a public model repository or object storage. It is usually a single gguf file (possibly with companion files like a tokenizer). This can be done with the pull command provided by your local inference tool, for example:
# Illustrative command; actual names and model identifiers depend on the tool you use<inference_tool> pull <repo_path>/<model_name>-4bit:tag
Step 2: Export the model description template.
Most local inference tools support “generating a description file from an existing model” to record the base model, inference parameters, and chat template. First export the original template as the starting point for modifications:
# Illustrative command<inference_tool> show --modelfile <model_name> > Modelfile.base
Step 3: Write the model description file (Modelfile).
A model description file describes a model using a declarative syntax similar to a Dockerfile. Common fields include:
FROM: the base model identifier, pointing to the pulled quantized model;PARAMETER: inference parameters, such as GPU offload layer count, context length, and sampling temperature;SYSTEM: the system prompt, defining the model’s role and output specifications;TEMPLATE: the chat template, which determines the input concatenation format (you can usually reuse the base model’s template directly).
The following example creates a copy that loads only some layers on the GPU. The model name is arbitrary:
# Create a copy from the 4-bit quantized modelFROM <repo_path>/<model_name>-4bit:tag# Limit the number of GPU-loaded layers: start with 18, adjust as neededPARAMETER num_gpu 18# Context length: 8K or more is recommended for Agent scenariosPARAMETER num_ctx 8192# Sampling parameters: lower temperature for more stable outputPARAMETER temperature 0.2PARAMETER top_p 0.9
Create and run:
# Create the copy (illustrative command)<inference_tool> create <custom_model_name> -f Modelfile# Run (illustrative command)<inference_tool> run <custom_model_name>
4.3 How to Choose the Layer Count: A Practical Tuning Method
There is no universal standard value for the number of GPU-offloaded layers; it depends on the model’s total layer count, VRAM capacity, and context length. Measure it step by step as follows:
- First record the total layer count. You can view it using the tool’s model information query command (such as
show <model_name>), or read it from the model card. - Estimate layers at about “half of VRAM.” For example, with 36 total layers and 12GB of VRAM, start from 18 layers.
- Adjust step by step and watch three metrics:
- Peak VRAM usage during inference (visible via tools like
nvidia-smi); - Generation speed (tokens/s);
- Whether an out-of-memory (OOM) error occurs.
- Peak VRAM usage during inference (visible via tools like
- Adjust by about 5% of VRAM headroom each time, until VRAM is nearly full but still has a small margin. This margin is used for context caching and concurrent requests.
- Also factor in context length. The longer the context, the more VRAM the KV cache uses, so when the context grows you should reduce the number of GPU layers accordingly. The two need to be tuned together.
A rule of thumb: treat VRAM as a budget and allocate it between “layers” and “context length.” Agent tasks usually need longer contexts, so you can reduce GPU layers and increase context length; for single-turn Q&A tasks, do the opposite.
5. Connecting to Coding Tools and Command-Line Agents
Once the local inference service is running, it usually exposes a compatible HTTP interface. Common paths include /v1/chat/completions (chat completions) and /v1/completions (text completions), and a model list query endpoint is often provided too. Most mainstream coding assistants and agent tools support custom inference endpoints, with configuration items typically including:
- Base URL: pointing to the local inference service address;
- API Key: local services usually require no authentication, so any placeholder value works;
- Model Name: fill in your custom copy’s name.
Example configuration (illustrative):
{"provider": "openai-compatible","base_url": "http://127.0.0.1:11434/v1","api_key": "local","model": "<custom_model_name>"}
Verify the interface is working:
# Query the list of loaded modelscurl http://127.0.0.1:11434/v1/models# Send a chat requestcurl http://127.0.0.1:11434/v1/chat/completions \-H "Content-Type: application/json" \-d '{"model": "<custom_model_name>","messages": [{"role": "user", "content": "Write a quicksort in Python"}],"temperature": 0.2}'
5.1 Tool Calling: The Link to Validate Most Carefully
Agent tools rely on the model outputting structured function calls (function calling / tool calling), including function names and JSON arguments. This is where local deployment most often goes wrong. Common problems include:
- Tool call format mismatch: The model’s output call format doesn’t match what the runtime environment expects, causing parsing to fail. Distilled models usually have built-in examples of a specific tool-call format, so confirm the inference backend can parse it correctly;
- Invalid argument JSON: The JSON generated by the model is missing fields, has the wrong types, or contains syntax errors;
- Context grows too long after multiple tool-call rounds: Each tool-call round appends results, quickly reaching the context limit.
Recommended order for troubleshooting and optimization:
- First test the call success rate with simple tools (like “read file” or “list directory”);
- If the failure rate is high, try appending a short system prompt in the model description file to clarify the tool-call format and argument specifications;
- Lower the temperature appropriately to reduce randomness;
- Set an upper limit on the context, and implement history truncation or summary compression on the agent side.
5.2 Keeping the Model Resident and Concurrency
- Keep-alive: The inference service may unload the model after a period of inactivity by default. Agent tasks often have dense but unevenly spaced requests, so set a longer keep-alive time to avoid frequent weight reloading;
- Concurrent requests: Single-GPU local inference has limited concurrency, so it’s generally not advisable to run multiple agent sessions at once. If you must run them concurrently, reduce each request’s context length, or separate tasks via container/process isolation.
6. Evaluating Results: Don’t Just Check “Can It Run?”
Being able to run doesn’t mean being good. After local deployment, use a small benchmark set for quantitative comparison instead of relying on gut feeling.
6.1 Building a Benchmark Set
Draw 30–50 typical tasks from your actual business, covering:
- Code generation and completion;
- Bug localization and fixing;
- Refactoring and code explanation;
- Script and configuration file generation;
- Multi-turn tool-calling tasks.
Record the reference answer or expected behavior for each task, and fix the temperature and sampling parameters during evaluation to ensure reproducibility.
6.2 Evaluation Dimensions
| Dimension | Description | Evaluation Method |
|---|---|---|
| Correctness | Whether the output meets the task requirements | Manual scoring or automated testing |
| Structure | Whether output follows the agreed format | Format validation |
| Tool-call success rate | Whether function calls are correct and arguments valid | Parse success rate statistics |
| Context utilization | Whether consistency holds under long contexts | Long-document task comparison |
| Generation speed | First-token latency, tokens/s | Load-testing tools |
6.3 Comparison Strategy
- Do an A/B comparison against the original API on the same task set, recording differences;
- Focus on “failure modes” rather than the average score: a local model may be clearly weaker than the API on complex reasoning tasks but nearly on par on simple, repetitive tasks;
- Adjust strategy based on failure modes: fully localize simple tasks, and fall back to the API for complex tasks.
7. Cost Decision: When Is Local More Cost-Effective?
The cost of local deployment isn’t just hardware procurement; it also includes electricity, depreciation, and operations labor. Use a simple break-even model to decide:
Total local deployment cost ≈ hardware investment / depreciation years + annual electricity + annual operations costTotal API cost ≈ annual number of calls × average tokens per call × unit price
Take a 24GB GPU, a whole-system power draw of about 500W, 8 hours of inference per day, and an electricity price of 0.6 CNY/kWh as an example:
- Annual electricity is about 876 CNY;
- With the hardware depreciated over 3 years, if the whole system costs 15,000 CNY, the average annual depreciation is 5,000 CNY;
- The total is about 5,900 CNY per year, not yet including operations labor.
In other words, local deployment has a clear cost advantage only when the annual API cost is clearly higher than this level. Also consider:
- Hidden costs: Model updates, troubleshooting, and security hardening all require labor;
- Capability gap: A small local model usually underperforms cloud LLMs on complex tasks, which may cause efficiency losses;
- Hybrid strategy: For most teams, the optimal solution isn’t “either/or” but a tiered routing of “simple tasks locally, complex tasks in the cloud.”
8. Common Issues and Troubleshooting
| Symptom | Likely Cause | Fix |
|---|---|---|
| VRAM overflow (OOM) | Too many GPU layers or too long a context | Reduce GPU layers, shorten context, lower concurrency |
| Extremely slow generation | Most layers computed on the CPU, or insufficient memory bandwidth | Increase GPU layers, close unnecessary background processes |
| Garbled or repetitive output | Quantization level too low or improper sampling parameters | Raise the quantization level, tune temperature and repetition penalty |
| Tool-call failure | Template mismatch or non-standard output format | Check inference backend template support, add system-prompt constraints |
| Slow first response | Model not kept resident, needs reloading | Set a longer keep-alive time |
| Quality drops after long conversations | Context exceeds the effective window | Truncate history, enable summary compression |
9. Summary
Replacing a paid API with a local 27B-class distilled model comes down to three things:
- Selection: Confirm the license is compliant and that the quantization level and context capability match your actual needs;
- Capacity: First budget VRAM and memory, then use layer offloading to trade for usable speed under limited VRAM;
- Integration and evaluation: Connect coding tools through a compatible interface, validate tool calling carefully, and use a small benchmark set for quantitative comparison.
Local deployment isn’t a “money-saving cure-all” but an engineering decision that requires trade-offs. For high-frequency, long-running, data-sensitive scenarios, its value often exceeds mere cost savings; for low-frequency, complex, quality-critical scenarios, a hybrid approach may be more suitable.
