Practical Guide to Open-Source LLMs: From Model Selection to Engineering Deployment

    A practical guide to adopting open-source large language models. It covers choosing between private deployment and hosted APIs, evaluating candidate models against real tasks, estimating GPU memory, selecting an inference framework, tuning concurrency, and setting up monitoring.

    1. Background: Why Open-Source Models Deserve Serious Attention

    Several organizations in China have recently released open-source models with large parameter counts or updated capabilities. Once the weights are public, developers can deploy, test, and modify these models in their own environments instead of relying entirely on external APIs. This lowers the technical barrier, but it also makes model selection more complicated.

    Public reports often cite parameter counts, cumulative download numbers, and leaderboard rankings. These figures show community interest and give a rough sense of model quality. They cannot tell you whether a model can solve your business problem. A high download count shows that many people tried the model. It does not show whether the model meets your accuracy, latency, and cost targets for a specific task. Before citing such numbers, confirm their source and how they were counted, then judge how much weight they deserve.

    2. Value and Risk: Do the Math First

    2.1 Key Benefits

    Open-source models offer four main benefits.

    • Data stays local: For scenarios involving customer records or internal documents, private deployment reduces how much data leaves your environment.
    • Customization: Fine-tuning, prompt templates, and retrieval-augmented generation (RAG) let the model adapt to business terminology and operating procedures.
    • Controllable cost: At high call volumes, self-hosted inference can cost less per request than pay-as-you-go APIs. Include hardware, electricity, and operations staff in the calculation.
    • Less dependence on a single vendor: If your business code calls models through a unified interface, switching models costs less.

    The trade-offs between deployment options are summarized below.

    Dimension Private Deployment Hosted API Hybrid
    Data sent externally None Yes, requires a data processing agreement Sensitive data stays private, and the rest goes through an API
    Upfront investment High, requires purchasing or renting GPUs Low, pay as you go Medium, requires maintaining two pipelines
    Operational responsibility Owned by the team Handled by the provider The team handles the private part
    Suitable scenarios Highly sensitive data, high call volume Prototyping, low call volume Balancing cost and compliance

    2.2 Key Risks

    • License terms: Commercial terms, usage restrictions, and attribution requirements differ widely between models. Have legal review each clause before launch. Do not rely only on the summary on the model page.
    • Weight integrity: After downloading, verify the SHA256 checksum published by the official source. For example, run sha256sum model.safetensors. Do not load the weights if the checksum does not match.
    • Capability limits: Strong results on some tasks do not guarantee stable performance across all languages, domains, and output formats.
    • Data compliance: Personal information in training data, logs, and caches needs a retention policy, and cross-border transfers need assessment. For finance, healthcare, and other regulated industries, confirm the applicable regulatory requirements.
    • Output safety: Production systems should add output filtering and content safety checks, and keep human review for critical operations.
    • Maintenance: Version upgrades, security patches, and performance regressions all require ongoing effort from the team.

    3. Model Selection: Start from Tasks, Not Leaderboards

    Follow these four steps.

    1. Define tasks: Break requirements into concrete tasks such as information extraction, long-document summarization, code completion, and multi-turn customer support. For each task, specify the input format, the output format, and how to handle failures.
    2. Build an evaluation set: Collect 100 to 300 real samples per task, covering normal, boundary, and abnormal inputs. Each sample includes an input and a reference answer. Store the samples in a JSONL file with one sample per line.
    3. Set scoring rules: Use scripts for tasks that can be judged automatically. For tasks that cannot, have two reviewers score independently and calculate Cohen’s Kappa. If Kappa is below 0.6, revise the scoring guidelines before continuing the evaluation.
    4. Compare cost and quality: Record pass rate, P50 and P95 latency, and cost per request together. Build a comparison table before making a decision.

    3.1 Evaluation Sample Format

    Each line contains one sample. Example:

    1. {"id": "001", "input": "What is the shipping address for order A1234? Output only the address.", "expected": "No. 100 Zhangjiang Road, Pudong New Area, Shanghai"}

    3.2 Evaluation Script

    The script below works with any inference service that exposes an OpenAI-compatible API. The endpoint, API key, and model name are read from environment variables, so no keys are stored in code.

    ```python
    import json
    import os
    import time
    from concurrent.futures import ThreadPoolExecutor, as_completed

    from openai import OpenAI

    BASE_URL = os.environ[“LLM_BASE_URL”] # For example, http://10.0.0.5:8000/v1
    API_KEY = os.environ[“LLM_API_KEY”] # Read from environment variables or a secrets manager
    MODEL = os.environ.get(“LLM_MODEL”, “candidate-model”)
    SAMPLE_PATH = os.environ.get(“SAMPLE_PATH”, “eval_samples.jsonl”)
    CONCURRENCY = int(os.environ.get(“EVAL_CONCURRENCY”, “8”))
    TIMEOUT_S = float(os.environ.get(“EVAL_TIMEOUT”, “60”))
    MAX_RETRIES = 3

    Disable the SDK’s built-in retries. This script controls retry count and backoff.

    client = OpenAI(base_url=BASE_URL, api_key=API_KEY, timeout=TIMEOUT_S, max_retries=0)

    def load_samples(path):
    with open(path, encoding=”utf-8”) as f:
    return [json.loads(line) for line in f if line.strip()]

    def judge(output, expected):

    1. # Example scoring: exact match after trimming leading and trailing whitespace.
    2. # For real tasks, replace this with a task-specific scoring function, for example
    3. # one that parses JSON and compares fields one by one, or one that uses a validated rule expression.
    4. return output.strip() == expected.strip()

    def call_model(prompt):
    last_error = None
    start = time.perf_counter()
    for attempt in range(MAX_RETRIES):
    try:
    resp = client.chat.completions.create(
    model=MODEL,
    messages=[{“role”: “user”, “content”: prompt}],
    temperature=0,
    max_tokens=512,
    )
    latency = time.perf_counter() - start
    return resp.choices[0].message.content or “”, latency, None
    except Exception as exc:
    last_error = str(exc)
    time.sleep(2 ** attempt) # Exponential backoff: 1 s, 2 s, 4 s
    return “”, time.perf_counter() - start, last_error

    def evaluate_one(sample):
    output, latency, error = call_model(sample[“input”])
    passed = error is None and judge(output, sample[“expected”])
    return {“id”: sample.get(“id”), “passed”: passed, “latency”: latency, “error”: error}

    def percentile(values, p):
    ordered = sorted(values)
    index = max(0, min(len(ordered) - 1, round(p / 100 * len(ordered)) - 1))
    return ordered[index]

    def