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.
python -m venv llm_envsource llm_env/bin/activate # On Windows use llm_env\Scripts\activatepip install --upgrade pip# For the torch install command, follow the PyTorch website selector and match your CUDA versionpip install torchpip install transformers accelerate peft datasetspip 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.
import osimport secretsimport timeimport uuidfrom typing import List, Literal, Optionalimport torchfrom fastapi import Depends, FastAPI, Header, HTTPExceptionfrom pydantic import BaseModel, Fieldfrom transformers import AutoModelForCausalLM, AutoTokenizerMODEL_PATH = os.environ.get("MODEL_PATH", "/data/models/your-model")API_KEY = os.environ["LLM_API_KEY"] # Read from environment variable; do not hard-codetokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)model = AutoModelForCausalLM.from_pretrained(MODEL_PATH,torch_dtype=torch.float16,device_map="auto",)model.eval()app = FastAPI()class Message(BaseModel):role: Literal["system", "user", "assistant"]content: str = Field(max_length=8000)class ChatRequest(BaseModel):model: strmessages: List[Message] = Field(min_length=1, max_length=50)max_tokens: int = Field(default=512, ge=1, le=2048)temperature: float = Field(default=0.7, ge=0.0, le=2.0)class ResponseMessage(BaseModel):role: strcontent: strclass Choice(BaseModel):index: intmessage: ResponseMessagefinish_reason: strclass ChatResponse(BaseModel):id: strobject: str = "chat.completion"created: intmodel: strchoices: List[Choice]def verify_key(authorization: Optional[str] = Header(default=None)):expected = f"Bearer {API_KEY}"if not secrets.compare_digest(authorization or "", expected):raise HTTPException(status_code=401, detail="invalid api key")@app.post("/v1/chat/completions",response_model=ChatResponse,dependencies=[Depends(verify_key)],)def chat(req: ChatRequest):messages = [m.model_dump() for m in req.messages]prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)inputs = tokenizer(prompt, return_tensors="pt", add_special_tokens=False).to(model.device)gen_kwargs = {"max_new_tokens": req.max_tokens,"pad_token_id": tokenizer.eos_token_id,}if req.temperature > 0:gen_kwargs.update(do_sample=True, temperature=req.temperature)else:gen_kwargs["do_sample"] = Falsewith torch.inference_mode():output_ids = model.generate(**inputs, **gen_kwargs)new_tokens = output_ids[0][inputs["input_ids"].shape[1]:]text = tokenizer.decode(new_tokens, skip_special_tokens=True)finish = "length" if len(new_tokens) >= req.max_tokens else "stop"return ChatResponse(id=f"chatcmpl-{uuid.uuid4().hex}",created=int(time.time()),model=req.model,choices=[Choice(index=0,message=ResponseMessage(role="assistant", content=text),finish_reason=finish,)],)
Set the key before starting the service, then run the server.
export LLM_API_KEY="replace-with-your-own-random-string"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
modelfield 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.
{"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.
import torchfrom datasets import load_datasetfrom peft import LoraConfig, get_peft_modelfrom transformers import (AutoModelForCausalLM,AutoTokenizer,DataCollatorForSeq2Seq,Trainer,TrainingArguments,)MODEL_PATH = "/data/models/your-model"DATA_PATH = "/data/train/qa_train.jsonl"OUTPUT_DIR = "/data/adapters/qa-lora-v1"MAX_LEN = 1024tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
