Chinese Open-Source LLM Deployment Guide: Four Core Capabilities and How to Evaluate Them
Chinese open-source LLMs have spread quickly across Chinese Q&A, code generation, document analysis, and enterprise knowledge base scenarios. Unlike closed models that only expose a hosted API, open weights let a team deploy, fine-tune, quantize, and extend a model inside its own environment — but open weights do not mean "ready to use." Developers still have to solve weight loading, GPU memory usage, inference latency, context management, output format validation, and multi-step orchestration. This guide follows a "how to choose, how to evaluate, how to operate" thread across five areas: open weights, instruction following, long-context understanding, and long-horizon tasks with deep research. It closes with a comparison of common Chinese model families, a reusable evaluation template, and a troubleshooting list for the failures teams hit most often: out-of-memory errors, unstable JSON output, weak retrieval, and drifting multi-step runs.
Chinese open-source LLMs are now widely used for Chinese Q&A, code generation, document analysis, and enterprise knowledge bases. Open weights allow teams to deploy, fine-tune, quantize, and build on a model in their own environment, but they do not remove the engineering work — weight loading, GPU memory footprint, inference latency, context management, output format validation, and multi-step task orchestration still have to be handled. This article covers how to choose, evaluate, and operate these models across five areas: open weights, instruction following, long-context understanding, and long-horizon tasks plus deep research. It also includes runnable Python examples, a comparison of common model families, a ready-to-use evaluation table, and a troubleshooting checklist for OOM, unstable JSON, inaccurate retrieval, and off-track multi-step runs.
1. Open Weights: From “Being Able to Call” to “Being in Control”
For an LLM, open weights mean the developer can obtain the parameter files and run inference in their own environment. The value shows up in three areas:
- Data control: sensitive data never has to leave the local environment, which suits finance, healthcare, government, and legal workloads with strict compliance requirements.
- Deep customization: you can instruction-tune the pretrained weights, adapt them to a domain, and compress them with quantization to produce a model purpose-built for a vertical scenario.
- Predictable cost: with existing compute in place, inference cost is relatively controllable, which fits long-running, steady traffic and batch workloads.
Open weights and closed APIs are not interchangeable, so selection should weigh several dimensions together:
| Dimension | Open weights | Closed API | Recommendation |
|---|---|---|---|
| Data compliance | Deployable locally, clear data boundary | Data must be sent to the provider | Prefer open weights for high-compliance scenarios |
| Upfront cost | Requires GPUs, operations, and engineering effort | Pay per call, fast to start | Use an API for quick validation; reassess self-hosting once stable |
| Latency and throughput | You can build your own batching, caching, and concurrency strategy | Subject to provider rate limits and network conditions | Load-test a self-hosted service for high-concurrency workloads |
| Controllability | Fine-tuning, quantization, custom prompts and toolchains | Depends on the provider’s versions and policies | Prefer open weights for deep business adaptation |
| Operations complexity | Requires monitoring, logging, alerting, and disaster recovery | Lower operational burden | Fill in the infrastructure before production |
Open weights are not barrier-free either. Before committing, confirm at minimum the model size, inference latency, GPU memory footprint, context length, fine-tuning resources, and read permission on the weight files. For a typical local deployment you generally need Python 3.9 or newer plus dependencies such as torch, transformers, and accelerate; some models additionally require sentencepiece or trust_remote_code enabled. If the model is large, evaluate up front whether you need INT8/INT4 quantization, KV Cache optimization, or multi-GPU sharding.
The code below is a minimal working example of loading weights and running inference. The MODEL_PATH value is read from an environment variable so the same code can be configured per environment.
import osfrom transformers import AutoModelForCausalLM, AutoTokenizer# Prefer an environment variable for the weight path to avoid hardcodingMODEL_PATH = os.getenv("MODEL_PATH", "./local-model-weights")tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH,trust_remote_code=True,)model = AutoModelForCausalLM.from_pretrained(MODEL_PATH,torch_dtype="auto",device_map="auto", # distribute across available devices automaticallytrust_remote_code=True,)def generate(prompt: str, max_new_tokens: int = 512) -> str:# Resolve the model's device so input tensors land in the right placedevice = next(model.parameters()).deviceinputs = tokenizer(prompt, return_tensors="pt").to(device)outputs = model.generate(**inputs, max_new_tokens=max_new_tokens)# Decode only the newly generated tokens, not the original promptgenerated = outputs[0][inputs["input_ids"].shape[-1]:]return tokenizer.decode(generated, skip_special_tokens=True)
In production, the application layer still needs timeout control, exception handling, logging, and retry on failure. If model loading fails, check whether the weight path is readable, whether dependency versions match, and whether GPU memory is exhausted. If inference fails, distinguish between input that is too long, abnormal output, and device errors.
2. Instruction Following: Turning “Understood the Request” into Verifiable Output
Instruction following determines whether a model can complete business tasks reliably. It is not just about answering a question; the model has to satisfy format, length, tone, field, and structure requirements under multiple constraints at once. Three metrics are worth tracking during evaluation:
- Constraint satisfaction rate: given “answer in three points, each under 20 characters,” does the model satisfy every constraint simultaneously?
- Format stability: how consistently the model produces structured output such as JSON, tables, or Markdown.
- Resistance to drift: in multi-turn conversations or long prompts, does the model drop earlier requirements?
Typical failures look like this: asked to output JSON only, it appends explanatory prose; asked for code and message fields, it omits one; asked to stay under 100 characters, it returns a long paragraph; asked to answer in Chinese, it slips in English. The standard engineering response combines three things: pin the constraints in a system prompt, validate at the application layer, and retry a bounded number of times.
The next example reuses the generate() function from the previous section and adds the json import, the input/output contract, and retry logic.
import jsonsystem_prompt = """You are a rigorous data-processing assistant.Every response must be valid JSON that contains exactly the fields code and message, with no extra text."""def safe_call(user_input: str, max_retries: int = 2) -> dict:full_prompt = system_prompt + "\n" + user_inputlast_error = ""for _ in range(max_retries + 1):raw = generate(full_prompt)try:data = json.loads(raw)if "code" in data and "message" in data:return datalast_error = "required field missing"except json.JSONDecodeError:last_error = "JSON parsing failed"# Feed the failure back to the model and ask for valid JSON onlyfull_prompt += f"\nNote: previous error: {last_error}. Output valid JSON only."return {"code": -1,"message": f"Invalid output format: {last_error}"}
If the model uses a chat template, put system_prompt into messages and build the final input with tokenizer.apply_chat_template() so it matches the model’s conversational format. For higher-assurance business flows, you can go further with JSON Schema validation, field type checks, content filtering, and human spot checks.
3. Long-Context Understanding: Not “It Fits,” but “It Finds and Connects”
Long-context ability is central to document analysis, contract review, report summarization, and knowledge Q&A. Many models accept a long context yet still degrade on recall of key information in the later part of a document, reasoning across paragraphs, and stability under long inputs. Three test categories are useful when evaluating this:
- Key information recall: place the answer at the beginning, middle, and end of the document and check whether the model retrieves it consistently.
- Cross-paragraph reasoning: require the model to combine clues scattered across several paragraphs to reach a conclusion.
- Context stability: observe whether answer quality drops noticeably as input length grows.
In practice, leaning on a very long context is not always the safest option. A more common pattern is “chunking + retrieval augmentation + controlled context assembly.” The example below is minimal but runnable. It depends on sentence-transformers; you can substitute a local embedding model, a vector database, or an internal vectorization service.
from sentence_transformers import SentenceTransformerimport numpy as np# Swap in a local Chinese embedding model or an internal vectorization serviceembedder = SentenceTransformer("BAAI/bge-small-zh-v1.5")def embed_fn(texts):return embedder.encode(texts, normalize_embeddings=True)def rank_by_relevance(chunks, query, embed_fn, top_k=5):query_vec = np.array(embed_fn([query])[0], dtype=np.float32)query_norm = query_vec / (np.linalg.norm(query_vec) + 1e-8)scored = []for chunk in chunks:chunk_vec = np.array(embed_fn([chunk])[0], dtype=np.float32)chunk_norm = chunk_vec / (np.linalg.norm(chunk_vec) + 1e-8)score = float(np.dot(query_norm, chunk_norm))scored.append((score, chunk))# Sort by relevance, highest first, and keep the top_k chunksscored.sort(key=lambda x: x[0], reverse=True)return [chunk for _, chunk in scored[:top_k]]def chunk_and_retrieve(document: str, query: str, chunk_size=1000):# Rough character-based split here; in production, count tokens with the tokenizerchunks = [document[i:i + chunk_size]for i in range(0, len(document), chunk_size)]ranked = rank_by_relevance(chunks, query, embed_fn, top_k=5)context = "\n".join(ranked)return f"Answer the question using the material below:\n{context}\n\nQuestion: {query}"
In production, chunk_size should not be chosen on character counts alone; it has to be derived from the model’s context budget. The simple formula is:
available context budget = max model input length - reserved output length - prompt template and instruction overhead
With an 8k context window, 1k reserved for output, and another 500 tokens consumed by the prompt and template, roughly 6500 tokens remain for retrieved chunks. At 1000 tokens per chunk that means 4 to 5 chunks. For very long documents, add overlapping windows, a reranking model, and source citations to reduce the risk of poor recall and insufficient evidence.
4. Long-Horizon Tasks and Deep Research: Decomposing Multi-Step Execution into Observable Flows
Long-horizon tasks are goals that require multi-step planning, sustained reasoning, and tool calls — for example, “research an industry and produce a structured report” or “derive a test plan from the requirements and run code checks.” Deep research capability means the model can decompose a problem on its own, gather information step by step, validate intermediate results, and finally assemble the output.
This puts higher demands on planning stability, tool-call reliability, and state management. Three mechanisms are recommended:
- Task decomposition: break a complex goal into independently executable sub-steps.
- State maintenance: persist each step’s plan, results, sources, and errors to form a traceable chain.
- Result validation: cross-check key intermediate conclusions to limit accumulating error.
The code below is explicitly labeled as pseudocode. llm_plan, llm_execute, is_goal_satisfied, and llm_summarize are abstract interfaces; a real project must replace them with concrete model calls, retrieval tools, a calculator, or a code execution environment.
# Pseudocode: the following are abstract interfaces and cannot be run directly.# A real project must replace them with model planning, tool execution,# termination checks, and result summarization.def llm_plan(state: dict) -> dict:# Input: current task state# Output: next plan, e.g. {"action": "search", "query": "material on <topic>"}raise NotImplementedError("replace with a model planning call")def llm_execute(plan: dict) -> dict:# Input: the plan from the previous step# Output: execution result, e.g. {"content": "search result", "source": "web/doc/database"}raise NotImplementedError("replace with retrieval, computation, or a tool call")def is_goal_satisfied(state: dict) -> bool:# Input: current task state# Output: whether the goal is met; can be judged by the model, by rules, or by samplingreturn Falsedef llm_summarize(findings: list) -> str:# Input: list of completed results# Output: final summary textraise NotImplementedError("replace with a summarization call")def deep_research(question: str, max_steps: int = 6) -> str:state = {"goal": question,"plan": [],"findings": [],"status": "running",}for _ in range(max_steps):plan = llm_plan(state)state["plan"].append(plan)result = llm_execute(plan)state["findings"].append(result)if is_goal_satisfied(state):state["status"] = "done"breakreturn llm_summarize(state["findings"])
Termination conditions should cover at least three cases: the goal is achieved, the maximum step count is reached, or an unrecoverable error occurs. In enterprise settings, also log the input, output, elapsed time, and tool-call result for every step to support audits and debugging. When evaluating long-horizon tasks, useful metrics include task completion rate, average number of steps, tool-call success rate, error accumulation rate, and final citation coverage.
5. Selection and Practice: How to Compare and Evaluate Chinese Open-Source Models
With many Chinese open-source models available, a team should not pick based on a single leaderboard. Build an evaluation system aimed at your own workload instead. The table below lists common model families as selection references only; actual capability and version details should follow the official model card and your own testing.
| Model family | Typical size range | Common fit | Deployment focus |
|---|---|---|---|
| Qwen2.5 series | 0.5B up to 72B and others | Chinese Q&A, structured output, code and general tasks | Check context length, quantization, and inference framework support |
| DeepSeek series | 7B, 67B, distilled variants, and others | Complex reasoning, code generation, analytical tasks | Inference cost is comparatively high; evaluate quantization and distillation |
| GLM-4 series | 9B and long-context variants, and others | Chinese comprehension, enterprise knowledge bases, office assistance | Check long-document handling and tool-call stability |
| InternLM series | 7B, 20B, and others | Lightweight deployment, Chinese office use, industry assistants | Check the deployment toolchain and community support |
Build an executable evaluation sheet rather than choosing by intuition. The template below is directly usable:
| Evaluation dimension | Key metrics | Suggested sample size | Example passing threshold | Deployment resource notes |
|---|---|---|---|---|
| Instruction following | Constraint satisfaction rate, valid JSON rate | 100 cases | Constraint satisfaction ≥ 85%, valid JSON ≥ 98% | A 7B model in BF16 needs roughly 16GB of GPU memory; 4-bit quantization lowers the footprint |
| Long-context understanding | Key information recall rate, cross-paragraph reasoning accuracy | 50 cases | Recall rate ≥ 80% at 8k/32k context | Long contexts raise memory use and latency substantially |
| Long-horizon tasks | Task completion rate, average number of steps | 30 tasks | Completion ≥ 70%, average steps ≤ 6 | Requires tool calls, logging, and retry mechanisms |
| Content safety | Sensitive-content block rate, privacy leakage rate | 200 cases | Zero serious incidents | Needs input filtering, output filtering, and audit logs |
| Performance stability | P95 latency, throughput, failure rate | 1000 load-test requests | P95 latency meets the business SLA | Watch concurrency, batching, and memory fragmentation |
Prepare for common failures and their fixes in advance:
- Out of memory (OOM): reduce batch size, shorten the context, enable INT8/INT4 quantization, use multi-GPU sharding, or move to a smaller parameter count.
- Unstable JSON output: pin the fields hard in the system prompt, add JSON Schema validation, and retry while logging the error.
- Inaccurate long-document retrieval: add chunk overlap, use a Chinese embedding model, rerank after recall, and cap the total context tokens.
- Off-track long-horizon tasks: add a step limit, validate each step’s result, log tool calls, and insert human review checkpoints.
Conclusion
The real value of Chinese open-source LLMs is not simply replacing a closed API. It is that an organization can build model capability that it controls around its own data, business needs, and compliance obligations. Open weights provide the foundation, instruction following determines usability, long-context understanding determines how deeply knowledge can be processed, and long-horizon capability determines the ceiling for complex scenarios. Three steps are a practical starting point: first, build an evaluation set that mirrors your business; second, run deployment load tests and cost analysis; third, put guardrails in place — format validation, content filtering, and failure retries. Only when model capability is turned into an engineering system that can be evaluated, operated, and iterated will an open-source LLM deliver stable value in real business work.
