Open-Weight AI Models: Local Deployment and Fine-Tuning Guide

    This guide explains what open-weight AI models are, how they differ from fully open-source AI, and why teams may choose self-hosted inference. It covers model selection, deployment preparation, an API wrapper, and LoRA fine-tuning, with practical code and operational cautions.

    More teams are moving beyond commercial API calls and running model files on their own servers. These are known as open-weight models. Their main value comes from three areas: long-term inference costs can be more controllable, business operations are less likely to be interrupted when a vendor changes prices or rate limits, and sensitive data can remain inside the corporate network. This article first explains the concept, then covers model selection, deployment, API wrapping, and fine-tuning.

    What Are Open-Weight Models?

    Open-weight models are models whose publisher releases the parameter files. Anyone can download these files and run, inspect, and modify them on their own hardware. Users do not have to depend on the publisher’s web interface or API, and can deploy, run inference, and fine-tune the model according to their own business requirements.

    Open-Weight vs. Fully Open-Source AI

    The industry often uses the two terms interchangeably, but they do not disclose the same things. Fully open-source AI requires the training data, training code, data filtering rules, and a reproducible training pipeline to be public. Open-weight models usually release only the final parameters; training data and the training pipeline may not be public.

    Comparison Item Open-Weight Model Fully Open-Source AI
    Model parameters Public Public
    Training code Not necessarily public Public
    Training data Usually not public Public or source-disclosed
    Data filtering rules Usually not public Public
    Reproducible training Generally not possible Possible
    Usage terms Determined by the specific license; some have scope restrictions Determined by the open-source license

    When selecting a model, read each license individually. Some licenses restrict commercial use, and some require separate authorization for companies above a certain user scale.

    Why Enterprises Should Consider Self-Hosted Inference

    Self-hosted inference mainly addresses three issues.

    Inference Cost

    For high-volume workloads, per-call API fees continue to grow. The cost of self-hosted inference mainly consists of hardware, electricity, and operations labor. Once the hardware is fixed, the marginal cost of handling each additional request is relatively low. However, if GPUs remain idle for long periods, self-hosting can actually be more expensive, so calculate costs based on actual call volume before launch.

    Vendor Dependency

    When a business depends on a single vendor, price changes, call-frequency limits, or service interruptions can directly affect operations. Keeping a replaceable local model allows switching if the vendor has problems. This is not zero risk, because the local service also requires dedicated maintenance.

    Data Compliance

    Before sending contracts, medical records, case materials, and similar data to a third-party API, legal and security teams usually need to review the process. Once the model is deployed on an internal network or private cloud, inference and fine-tuning data can remain within the enterprise boundary. However, access control, log management, and backups still need to be handled by the team.

    How to Choose a Model

    Larger models usually have stronger understanding capabilities, but they also require more VRAM. The following estimate can help determine whether a single GPU can run a model.

    Rough inference VRAM estimate formula: parameters in billions × bytes per parameter × 1.2. In FP16 precision, each parameter occupies 2 bytes; after 4-bit quantization, it occupies about 0.5 bytes. The 1.2 factor reserves headroom for activations and KV cache. The longer the context, the more memory is actually used.

    Parameter Scale Rough FP16 VRAM Suitable Scenarios Notes
    7B to 8B About 17 GB Single-GPU experiments, simple customer-support Q&A, classification Limited complex reasoning capability
    13B to 14B About 31 GB Knowledge-base Q&A, document summarization Requires a single GPU with more VRAM or two GPUs
    70B class About 170 GB or more Complex reasoning, long-document analysis Usually requires multiple GPUs or quantized deployment

    When choosing a model, also check four points: whether the license permits your use case, whether it supports the languages and coding capabilities you need, whether community maintenance is active, and whether the official release provides a matching chat template.

    What to Prepare Before Deployment

    Deploying a large language model requires GPUs. You can purchase local GPU servers or use GPU instances from major cloud providers. In either case, prepare three things first.

    First, enough disk space to store the weight files. Second, install an NVIDIA driver and CUDA version that match the PyTorch version. After installation, run nvidia-smi to confirm that the GPU and VRAM are visible. Third, monitoring tools to record VRAM usage, GPU utilization, and service availability.

    Model weight files are large. It is recommended to place them in a separate directory and restrict permissions so that only the service account can read them.

    How to Install Dependencies

    The following commands create a virtual environment and install common libraries.

    1. python -m venv llm_env
    2. source llm_env/bin/activate # On Windows use llm_env\Scripts\activate
    3. pip install --upgrade pip
    4. # For the torch install command, follow the PyTorch website selector and match your CUDA version
    5. pip install torch
    6. pip install transformers accelerate peft datasets
    7. pip install fastapi uvicorn pydantic

    After dependencies are installed and tested, run pip freeze > requirements.txt to pin versions. Do not copy version numbers directly from an article, because they have not been verified in your environment.

    How to Wrap the Model as an API

    The following service wraps a local model in a simplified chat endpoint. Its request and response structures reference the OpenAI chat format, but only part of it is implemented. It does not support streaming output, tool calls, or usage statistics, so it cannot directly replace clients that depend on full compatibility.

    1. import os
    2. import secrets
    3. import time
    4. import uuid
    5. from typing import List, Literal, Optional
    6. import torch
    7. from fastapi import Depends, FastAPI, Header, HTTPException
    8. from pydantic import BaseModel, Field
    9. from transformers import AutoModelForCausalLM, AutoTokenizer
    10. MODEL_PATH = os.environ.get("MODEL_PATH", "/data/models/your-model")
    11. API_KEY = os.environ["LLM_API_KEY"] # Read from environment variable; do not hard-code
    12. tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
    13. model = AutoModelForCausalLM.from_pretrained(
    14. MODEL_PATH,
    15. torch_dtype=torch.float16,
    16. device_map="auto",
    17. )
    18. model.eval()
    19. app = FastAPI()
    20. class Message(BaseModel):
    21. role: Literal["system", "user", "assistant"]
    22. content: str = Field(max_length=8000)
    23. class ChatRequest(BaseModel):
    24. model: str
    25. messages: List[Message] = Field(min_length=1, max_length=50)
    26. max_tokens: int = Field(default=512, ge=1, le=2048)
    27. temperature: float = Field(default=0.7, ge=0.0, le=2.0)
    28. class ResponseMessage(BaseModel):
    29. role: str
    30. content: str
    31. class Choice(BaseModel):
    32. index: int
    33. message: ResponseMessage
    34. finish_reason: str
    35. class ChatResponse(BaseModel):
    36. id: str
    37. object: str = "chat.completion"
    38. created: int
    39. model: str
    40. choices: List[Choice]
    41. def verify_key(authorization: Optional[str] = Header(default=None)):
    42. expected = f"Bearer {API_KEY}"
    43. if not secrets.compare_digest(authorization or "", expected):
    44. raise HTTPException(status_code=401, detail="invalid api key")
    45. @app.post(
    46. "/v1/chat/completions",
    47. response_model=ChatResponse,
    48. dependencies=[Depends(verify_key)],
    49. )
    50. def chat(req: ChatRequest):
    51. messages = [m.model_dump() for m in req.messages]
    52. prompt = tokenizer.apply_chat_template(
    53. messages, tokenize=False, add_generation_prompt=True
    54. )
    55. inputs = tokenizer(
    56. prompt, return_tensors="pt", add_special_tokens=False
    57. ).to(model.device)
    58. gen_kwargs = {
    59. "max_new_tokens": req.max_tokens,
    60. "pad_token_id": tokenizer.eos_token_id,
    61. }
    62. if req.temperature > 0:
    63. gen_kwargs.update(do_sample=True, temperature=req.temperature)
    64. else:
    65. gen_kwargs["do_sample"] = False
    66. with torch.inference_mode():
    67. output_ids = model.generate(**inputs, **gen_kwargs)
    68. new_tokens = output_ids[0][inputs["input_ids"].shape[1]:]
    69. text = tokenizer.decode(new_tokens, skip_special_tokens=True)
    70. finish = "length" if len(new_tokens) >= req.max_tokens else "stop"
    71. return ChatResponse(
    72. id=f"chatcmpl-{uuid.uuid4().hex}",
    73. created=int(time.time()),
    74. model=req.model,
    75. choices=[
    76. Choice(
    77. index=0,
    78. message=ResponseMessage(role="assistant", content=text),
    79. finish_reason=finish,
    80. )
    81. ],
    82. )

    Set the key before starting the service, then run the server.

    1. export LLM_API_KEY="replace-with-your-own-random-string"
    2. uvicorn api_server:app --host 127.0.0.1 --port 8000

    A few notes:

    • The service listens only on the local address. External access should go through a reverse proxy with HTTPS enabled.
    • The model field in the request is only echoed back; the service does not switch models based on it.
    • The code uses tokenizer.apply_chat_template, so the model must include a chat template. If it is missing, use a version with a template or configure one manually.
    • The generation function is synchronous, so requests on the same GPU will queue. For high concurrency, use a dedicated inference server such as vLLM or TGI.
    • Do not write raw prompts to logs, or redact sensitive information first.

    How to Fine-Tune with LoRA

    LoRA trains only a small set of additional low-rank matrices while keeping the original model parameters frozen. This reduces VRAM usage, and the resulting adapter files are only tens to hundreds of megabytes, making version management easier.

    Prepare Data

    Training data uses JSONL format, with one dialogue sample per line. The last message must be the assistant’s answer.

    1. {"messages": [{"role": "system", "content": "You are an enterprise knowledge base assistant. Answer only based on the provided materials."}, {"role": "user", "content": "How many days of annual leave do employees have after one year but less than ten years of service?"}, {"role": "assistant", "content": "They receive 5 days of annual leave per year."}]}

    A few hundred rows are recommended at minimum, and the data should cover real business questions. With too little data, the model tends to memorize samples rather than generalize. Sensitive information in the data should be redacted first.

    Training

    The names of target_modules vary by model architecture. q_proj and v_proj shown above are common names; before use, run print(model) to confirm the layer names.

    1. import torch
    2. from datasets import load_dataset
    3. from peft import LoraConfig, get_peft_model
    4. from transformers import (
    5. AutoModelForCausalLM,
    6. AutoTokenizer,
    7. DataCollatorForSeq2Seq,
    8. Trainer,
    9. TrainingArguments,
    10. )
    11. MODEL_PATH = "/data/models/your-model"
    12. DATA_PATH = "/data/train/qa_train.jsonl"
    13. OUTPUT_DIR = "/data/adapters/qa-lora-v1"
    14. MAX_LEN = 1024
    15. tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)