Deploying Distilled Open-Source LLMs Locally: A Complete Guide to Small Models (2B, 9B, 27B)
Cloud providers often distill their flagship LLMs into smaller open-source models in sizes like 2B, 9B, and 27B. This guide explains how these distilled models are built and what they can realistically do, how to choose and integrate local inference tooling, and how to balance VRAM, long context, and generation speed. It also walks through driving a coding agent with a distilled model, a hybrid cloud-local architecture, and a checklist of common pitfalls. Readers will find practical guidance on quantization, KV cache sizing, dual-compatible APIs, and stability engineering for reliable local LLM deployment.
Introduction: From “Strongest in the Cloud” to “Good Enough Locally”
Over the past couple of years, many cloud providers have distilled their flagship LLMs into smaller open-source models in the same family, often released in sizes like 2B, 9B, and 27B. The core selling point of these “distilled” models is clear: they migrate part of the capability of a cloud model down to a size that runs on your own machine, giving developers a “good enough” local model that works without an internet connection and without your data ever leaving the device.
On the question of whether a 9B model is actually usable, published third-party benchmarks offer a useful reference point:
- A community-released 27B version runs stably on a single consumer flagship GPU with 24 GB of VRAM.
- Combined VRAM usage for weights and runtime is around 16.5 GB.
- Generation speed is roughly 29-35 tokens/s.
- The advertised context window is 262K, enough to cover everyday needs.
These numbers were measured under specific hardware, quantization, and parameter settings. Don’t treat them as a universal benchmark; treat them as a starting point for estimating your own setup.
This article addresses four questions:
- Where are the capability limits of a distilled model?
- How should you choose and integrate local inference tooling?
- How do you trade off VRAM, long context, and generation speed?
- How do you connect a distilled model to a coding agent while keeping its output stable?
1. First, the Fundamentals: What Is a Distilled Model and What Can It Do?
1.1 How Knowledge Distillation Works
Knowledge distillation was introduced by Hinton et al. in 2015. The core idea is to “have a student model imitate a teacher model.” The teacher is usually a larger, stronger model; the student is the smaller model you actually want to deploy.
During training, the teacher’s output probability distribution is called soft labels. For example, for three classes “cat, dog, wolf,” a hard label only tells the student “the answer is cat,” whereas a soft label also conveys inter-class similarity information such as “dog is slightly more probable than wolf” - far richer than a single label. The student’s optimization objective is typically a weighted combination of KL-divergence loss over the soft labels and cross-entropy loss against the true labels.
Most “distilled” models in the open-source community use a data-driven variant:
- First, have a strong model generate answers, and sometimes full reasoning traces, for a large volume of instructions.
- Then use this synthetic data as supervised fine-tuning material to train a same-family open-source base model.
This approach has a low barrier to entry and shows results quickly, so it is widely used. A model family tiered by parameter count (2B/9B/27B) usually shares similar architecture, tokenizer, and system-prompt templates, with capability increasing along with parameter count. A unified toolchain therefore transfers between tiers at low cost.
1.2 Key Insight: Distillation Transfers “Style and Habits,” Not Just “Knowledge”
It’s important to be clear-eyed here: distillation primarily transfers the teacher’s response style, task habits, and instruction-following patterns - it does not replicate its reasoning ability. On tasks like instruction following, code rewriting, and document writing, distilled models can often approach the teacher’s level quickly; but in situations that require rigorous multi-step reasoning (such as complex algorithm design or cross-module architectural refactoring), the capability gap widens rapidly as problem difficulty increases.
Common issues include:
- Logical chains that skip steps midway.
- More factual errors in long-form text.
- Hallucinations about newer frameworks or obscure libraries not covered in the training data.
So the question “what can a distilled model do” has no single answer - it depends on whether the task distribution overlaps with the distillation data. When selecting a model, run a small-scale evaluation on your own business samples first, rather than looking only at general leaderboards.
1.3 Matching Parameter Tiers to Scenarios
| Parameter size | Capability (rule of thumb) | Recommended scenarios |
|---|---|---|
| 2B | Lightweight entry | Function-level completion, text rewriting, simple Q&A; terminal-side applications sensitive to latency and power |
| 9B | Everyday usable | Code changes in a single file or a few files, error explanation, comment and documentation generation |
| 27B | Higher capability ceiling | Coding tasks with some reasoning depth, longer-context understanding, quality-first offline scenarios |
2B suits validating your toolchain and fast iteration, 9B is the “value sweet spot,” and 27B is the balance point between quality and resources.
2. Local Inference Tooling: Selection Criteria and Integration
2.1 Trade-offs Among Three Deployment Paths
Running an open-source model locally usually means one of three approaches:
- Code-level invocation: Use an inference framework’s API to embed the model into an application service. This gives the most control but requires you to manage model downloads, device scheduling, and concurrency queues yourself, so development cost is higher.
- Command-line service: Start a persistent service from the command line and have other programs call it through an interface. Lightweight and controllable, suited to server environments, but less intuitive to debug.
- Graphical desktop tools: Provide model download management, parameter tuning, a chat UI, and a local API service. Quick to get started and highly visual, suited to individual developers and rapid validation by small-to-mid teams.
For the distilled models discussed here, a graphical tool is the lowest-cost starting point. The “easy to deploy” feedback in published tests comes from exactly this.
2.2 Key Capabilities to Look For in a Graphical Tool
When evaluating a graphical inference tool, focus on these capabilities:
- Model acquisition and version management: Search, download, and update models by quantization level, and switch quickly between models.
- GPU layer offloading: Adjust how many model layers load into VRAM. When VRAM is insufficient, the remaining layers automatically fall back to system memory and the CPU, trading speed for feasibility.
- Visual control of quantization level and context length: Directly compare VRAM usage and speed across settings instead of trial and error.
- System-prompt and inference-parameter management: Save parameters like temperature and max output length as presets for easy reuse within a team.
- Real-time metrics: At-a-glance visibility into VRAM and memory usage, tok/s, time to first token, and other key indicators.
Together these capabilities lower the bar for “install it, run it, tune it” and are what let developers without an algorithm background deploy independently.
2.3 Dual-Compatible API: Smooth Integration With Existing Toolchains
Tools like this typically expose an HTTP API locally and support both of the industry’s mainstream chat-interface styles:
- General chat-completion style: Built around a
messagesarray, using arolefield to distinguish system, user, assistant, and other roles. Many client libraries, scripts, and open-source apps support this style natively. - A message style featuring content blocks and a separate system parameter: Some commercial models offer an API with a similar design. Supporting this style as well means the relevant coding-assistant tools only need to change the service address and a placeholder key to point at a local model.
The practical value is:
- The same agent code can connect to either a cloud LLM or a local distilled model.
- When dealing with sensitive code, you only need to switch the endpoint to keep the inference step inside your network.
- It makes A/B evaluation around the same interface easy, for side-by-side comparison of different models.
Compatibility also has boundaries:
- Extended capabilities like function (tool) calling, streaming output, and structured output are supported to varying degrees across tools.
- Whether a model can reliably emit valid function-call arguments depends more on whether the model itself was trained for it than on whether the interface is compatible.
- After switching backends, always re-verify tool-calling, multi-turn conversation, and error-code handling logic.
2.4 Sample Code: A Unified Interface Wrapper
To let an upper-layer agent switch between local and cloud backends transparently, collapse the integration layer into a thin wrapper:
import requests# Illustrative only; fields and response structure may differ across products. Refer to the actual API documentation.def chat(base_url: str, api_key: str, model: str,messages: list[dict], temperature: float = 0.2) -> str:resp = requests.post(f"{base_url}/chat/completions",headers={"Authorization": f"Bearer {api_key}","Content-Type": "application/json"},json={"model": model, "messages": messages,"temperature": temperature},timeout=120,)resp.raise_for_status()return resp.json()["choices"][0]["message"]["content"]# Local service: fill in the address and key per your local inference service configurationanswer = chat("http://127.0.0.1:8000/v1", "local", "local-model",[{"role": "user", "content": "Implement quicksort in Python"}])print(answer)
With this, you can switch the target at the configuration layer - a local service or a cloud model service - with no changes to business code. Read keys uniformly from environment variables or a config center, and never hardcode them into source.
3. VRAM and Speed: The Triangle of Quantization, KV Cache, and Long Context
3.1 VRAM Cost of Weights
VRAM usage for weights is approximately “parameter count × bytes per parameter”:
- FP16: 2 bytes per parameter.
- 8-bit quantization: about 1 byte.
- 4-bit quantization: about 0.5 byte, plus a small amount of auxiliary data such as scaling factors and zero points.
A 27B model quantized to 4-bit uses roughly 14-16 GB for weights. Add the inference engine’s runtime overhead, framework VRAM, and KV cache, and the measured 16.5 GB is broadly consistent with the theoretical estimate.
3.2 The Often-Overlooked KV Cache
During inference, attention at each layer needs the Key and Value vectors of all previous tokens; caching these vectors is the KV cache. Its size is:
VRAM ≈ 2 × layers × KV heads × head dim × bytes per element × sequence length
Unlike parameters, the KV cache grows linearly with context length and the number of concurrent requests, and it is not fully covered by the “compression benefit” of weight quantization. It matters especially for long-context scenarios. You can quickly estimate the order of magnitude with the following (the sample values only illustrate scale and do not represent any specific model):
def kv_cache_gb(layers, kv_heads, head_dim, bytes_per_elem, seq_len):return 2 * layers * kv_heads * head_dim * bytes_per_elem * seq_len / 1024**3# Illustrative: 48 layers, 8 KV heads, head dim 128, storing KV in FP16 and 8-bit respectivelyfor bpe in (2, 1):print(f"{bpe * 8}bit KV:")for n in (4096, 32768, 262144):print(f" context {n:>6}: {kv_cache_gb(48, 8, 128, bpe, n):.2f} GB")
Assuming weights and runtime together use about 16.5 GB, and even though actual execution also uses techniques like grouped-query attention to compress the KV cache, a 262K window still cannot fit entirely in a single 24 GB GPU. How long a context you can actually support depends on the real architecture, cache precision, and scheduling strategy. In other words, the advertised context length and “how much you can actually ingest at once” are not the same thing.
3.3 Choosing a Quantization Level
- 4-bit: Lowest VRAM usage, suited to a consumer GPU running the 27B tier; quality loss on general tasks is usually limited, though complex reasoning may degrade somewhat.
- 8-bit: Quality closer to full precision, but VRAM usage roughly doubles; for a 27B model on a 24 GB GPU, the space left for the KV cache is noticeably compressed.
- More aggressive low-bit quantization: Saves more VRAM but carries greater risk of quality fluctuation; use only after evaluation passes.
3.4 Long Context: Advertised Length Is Not Effective Length
Even if VRAM allows scaling to hundreds of thousands of tokens, that doesn’t mean the model uses information uniformly across the whole window. Research in the field (such as “Lost in the Middle”) shows that models make markedly less use of information in the middle of a long text than at the beginning and end.
Practical advice:
- Inject only code and documentation directly relevant to the task.
- Use retrieval to narrow the context; for long documents, use “section summaries + recall of key snippets.”
- Place key information (such as the raw error text or target files) at the start and end of the context.
3.5 The Hardware Factors Behind Speed
The 29-35 tokens/s figure is already enough to support interactive coding on a single GPU. The main factor determining speed is memory bandwidth, not compute: during decoding, the engine reads the entire set of weights for every token it generates.
This leads to two practical conclusions:
- Generation speed varies mainly with parameter count and quantization precision; long context adds overhead to the prefill stage and to per-step attention computation. Under long prompts, time to first token increases noticeably, but the per-token generation speed drops relatively little.
- Raising speed through more aggressive quantization is essentially “moving the weights with fewer bits”; the cost is lower quality.
3.6 A Multi-Dimensional Reading of the 27B Test Results
“Runs smoothly on a single GPU” means:
- Lower deployment barrier: No multi-GPU parallelism or split inference, so no complex parallel configuration.
- Usable interaction: Around 30 tokens/s is roughly at reading speed, so continuous conversation doesn’t stall noticeably.
- Long context still comes at a cost: The advertised 262K is a model-level ceiling. VRAM headroom must be reserved for the KV cache and the OS, and prefill latency also rises with long context; when putting it into practice, weigh context size against the specific task.
4. Real-World Scenario: A Distilled Model Driving a Coding Agent
4.1 The Typical Coding-Agent Workflow
Unlike the “one question, one answer” chat mode, a coding agent runs a multi-step closed loop around the model:
- Read a compile error or failing test log.
- Locate the relevant source files.
- Generate the change and write it to a file.
- Recompile or rerun the tests.
- Keep correcting based on the results.
- Once the task is done, generate or update documentation.
This loop usually involves ten or more model calls, sometimes many more, which imposes three demands on the model:
- Instruction following: Return results strictly in the required output format (such as a unified patch format or structured JSON).
- State management: Keep context consistent across multiple tool-result turns without “forgetting” the original goal as history grows.
- Recoverability: When it hits a format error or a tool failure, self-correct from the feedback rather than getting stuck in a loop.
4.2 The Distilled Model in Practice
Published test feedback says the distilled model is stable in the above scenarios:
- It can automatically read errors and locate the problem.
- It can modify code and write a README.
- Throughout the process it “doesn’t stall.”
“Don’t stall” means both that generation speed is steady with no obvious pauses and that the task advances without frequent interruptions or repeated failures. The 9B tier already covers a fair share of everyday tasks; when you want more complex reasoning, the 27B tier usually gives more reliable results.
4.3 Evaluation Dimensions
To assess a distilled model’s usability in a coding agent, build your own evaluation set along these dimensions:
- Error fixing: Given a compile or runtime error, can it locate the right file and line in one go?
- Compliant code changes: Can it output changes in a unified patch format?
- Instruction following: Can it strictly obey constraints like “only change the specified function” or “don’t introduce new dependencies”?
- Documentation generation: Can it generate an accurate README from the real code structure, rather than piling on templates?
- Multi-turn coherence: After several consecutive tool calls, does it still remember the original goal?
- Failure recovery: When a tool errors or a patch is malformed, can it correct itself?
4.4 Stability Engineering: Don’t Rely on the Model’s “Self-Discipline”
Even the most stable model needs outer safeguards:
- Structured output: Fix an output protocol (such as a JSON Schema) in the system prompt and validate the returned content by parsing it; on parse failure, feed the error back to the model to retry, while capping the number of retries.
- Tool whitelist: Only allow reading and writing files within the working directory and running agreed commands, to prevent the agent from “going out of bounds.”
- Timeouts and quotas: Set a timeout and token cap for each step to prevent long contexts from dragging out responses.
- Observability: Log a summary of each turn’s prompt, output length, latency, and token consumption, to make it easy to pinpoint “which step got stuck.”
5. A Hybrid Architecture of Cloud and Local
The value of deploying a distilled model locally isn’t to “replace the cloud LLM” but to form a layered collaboration:
- Local layer: Handles high-frequency, low-sensitivity, or time-sensitive tasks like code completion, error explanation, and comment and documentation generation, with data never leaving the machine.
- Cloud layer: Takes on high-difficulty tasks like complex reasoning and cross-repository refactoring; the local model can serve as a draft generator, then a stronger model reviews and refines it.
On the cloud side, general cloud capabilities can help engineer this architecture:
- Container platform: Containerize the inference service and scale elastically on demand.
- Object storage: Centrally manage model files and datasets.
- Logging, monitoring, and alerting: Accumulate call chains and performance metrics to catch anomalies quickly.
Baidu AI Cloud’s Qianfan model platform offers capabilities for model development, training, deployment, and invocation, letting enterprises choose a cloud-and-local combination based on their business needs.
6. FAQ and a Pitfall Checklist
- Repetitive output or getting stuck in loops
Lower the temperature a bit, enable repetition penalties, and state in the system prompt to “end immediately once output is complete.” - Malformed patches
Give a strict format example in the prompt, and validate the output by parsing plus automatic retry. - Sharp slowdown under long context
Usually prefill-stage overhead; shrinking the context, processing in segments, or enabling cache reuse can significantly improve time to first token. - VRAM overflow
First lower the quantization level or reduce the number of offloaded GPU layers; for long context, reserve extra space for the KV cache. - Unstable function calling
Before local deployment, verify the model was trained for tool calling - don’t assume interface compatibility equals capability. - Large gap between local and cloud behavior
The system-prompt templates, sampling parameters, and context-trimming strategies may differ between the two; unify these settings before comparing. - Data security
A local model still needs access control; a local API may not verify keys by default, so you must add authentication before exposing it to a LAN or the public internet.
Conclusion
Deploying a distilled model locally is essentially an engineering trade-off between “capability density” and “hardware cost”:
- Small models gain a near-large-model interaction experience through distillation.
- Quantization squeezes the VRAM requirement into a consumer GPU.
- A dual-compatible API lets existing toolchains migrate smoothly.
- A coding agent amplifies this capability across multi-turn loops.
A 27B tier running smoothly on a single GPU and a 9B tier already meeting everyday needs show that “locally usable” is no longer a niche experiment. The next optimization directions lie in smarter context organization, stricter tool-calling constraints, and dynamic routing between cloud and local.
