Deploying Open-Source LLM Weights: Setup, Fine-Tuning, and Inference Optimization

    A practical guide to deploying open-source LLM weights: how to verify license compliance, estimate GPU memory, run local inference, fine-tune with LoRA/QLoRA, and optimize production serving with engines like vLLM.

    1. Verify the Weight Source and License First

    Open weights do not automatically mean unrestricted commercial use. Before downloading, confirm three things:

    • Publisher and download source: Download only from the official repository or a certified mirror, and verify the SHA256 hash of the files.
    • License type: Apache 2.0, MIT, and similar licenses generally allow commercial use. Custom licenses often include user-count limits, prohibited use cases, or attribution requirements—have your legal team review them.
    • Model Card: Check the training data description, evaluation results, known limitations, recommended prompt format, and hardware requirements.

    This article is not tied to a specific model. Paths, parameters, and configuration examples should be replaced with the actual values of the model you choose, following its official documentation.

    2. Resource Planning for Private Deployment

    A basic rule of thumb for GPU memory: parameter count multiplied by bytes per parameter. In bf16, each parameter takes 2 bytes, so a 7B model needs roughly 14 GB for weights, and a 70B model about 140 GB. With INT4 quantization, each parameter takes roughly 0.5 bytes, so a 7B model’s weights fit in about 3.5 GB.

    This covers weights only. KV cache, activations, and framework overhead require additional headroom, and these grow significantly with long contexts and high concurrency. The table below is a rough reference; final configurations should be based on your own load testing.

    Model size bf16 weights INT4 weights Reference setup
    7B ~14 GB ~4 GB Single 24 GB GPU
    14B ~28 GB ~8 GB Single 40/48 GB GPU, or two GPUs
    70B ~140 GB ~40 GB Multiple 80 GB-class GPUs, or two GPUs after quantization

    1. Pin Dependency Versions

    Specify exact versions of libraries such as torch, transformers, accelerate, and peft in your requirements.txt, matching the model card’s requirements. Without pinned versions, the same code may behave differently across deployments.

    2. Load Weights and Run an Inference Test

    1. import torch
    2. from transformers import AutoModelForCausalLM, AutoTokenizer
    3. model_path = "/data/models/your-model" # Replace with your actual local weight path
    4. tokenizer = AutoTokenizer.from_pretrained(model_path)
    5. model = AutoModelForCausalLM.from_pretrained(
    6. model_path,
    7. torch_dtype=torch.bfloat16,
    8. device_map="auto", # Automatically shard the model across available GPUs
    9. )
    10. model.eval()
    11. # Place the input tensor on the device of the model's first layer to avoid multi-GPU issues
    12. inputs = tokenizer("How can open-source models optimize enterprise business processes?", return_tensors="pt").to(model.device)
    13. with torch.no_grad():
    14. outputs = model.generate(**inputs, max_new_tokens=200)
    15. # Decode only the newly generated tokens, excluding the input prompt
    16. new_tokens = outputs[0][inputs["input_ids"].shape[1]:]
    17. print(tokenizer.decode(new_tokens, skip_special_tokens=True))

    Usage notes:

    • trust_remote_code=True executes custom code from the repository. Keep it off by default; enable it only when the model truly requires it, after reviewing the code and pinning a specific commit.
    • To restrict visible GPUs, set CUDA_VISIBLE_DEVICES=0,1 before launching.

    3. Output Safety Filtering

    Model outputs should never be returned to users directly. Add a filtering layer on the output side to check for sensitive terms, personal information, and obviously prohibited content. User inputs must also be sanitized before being written to logs.

    3. LoRA Fine-Tuning Checklist

    LoRA trains only a small set of low-rank matrices, using far less GPU memory than full-parameter fine-tuning—ideal for teams with limited compute. QLoRA quantizes the base model to 4 bits before training, further reducing memory, though training is typically slower.

    1. Prepare the Data

    Use JSONL format, one sample per line:

    1. {"messages": [{"role": "system", "content": "You are a contract review assistant"}, {"role": "user", "content": "Point out the risks in the following clause: ..."}, {"role": "assistant", "content": "This clause has the following risks: ..."}]}

    Key points for data preparation:

    • Volume: For domain-specific tasks, start with a few hundred high-quality samples. Validate the approach at small scale first, then expand.
    • Splitting: Divide data into training, validation, and test sets; typically reserve 5–10% for validation.
    • Cleaning: Remove duplicates, delete or replace content containing personal information, and unify formats and labeling standards.
    • Compliance: When customer data is involved, complete anonymization first and confirm that data usage complies with local regulations and internal policies.

    2. Configure Training Parameters

    The following are common starting points; adjust based on validation results:

    • LoRA rank r=16, lora_alpha=32, lora_dropout=0.05
    • Learning rate between 1e-4 and 2e-4
    • Train for 1 to 3 epochs
    • Target modules (target_modules) depend on the model architecture—inspect the model’s layer names to determine them
    1. from peft import LoraConfig, get_peft_model
    2. lora_config = LoraConfig(
    3. r=16,
    4. lora_alpha=32,
    5. lora_dropout=0.05,
    6. target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], # Adjust based on model architecture
    7. task_type="CAUSAL_LM",
    8. )
    9. model = get_peft_model(model, lora_config)
    10. model.print_trainable_parameters()

    3. Evaluate the Results

    • Overfitting monitoring: Track both training and validation loss during training. If training loss keeps falling while validation loss rises, the model is overfitting—stop early or reduce the number of epochs.
    • General capability regression: Prepare a set of general test questions covering instruction following and common-sense QA, and compare scores before and after fine-tuning. A clear drop indicates catastrophic forgetting; adjust data mixing or learning rate.
    • Business test set: Score real business samples manually, tracking accuracy, refusal rate, and output format compliance.

    4. Inference Optimization and Cloud-Native Deployment

    1. Choose an Inference Engine

    Calling generate directly is fine for debugging but not for high-concurrency services. Production environments typically use inference engines such as vLLM or TGI. Their two key techniques are:

    • PagedAttention: Manages the KV cache in blocks, reducing memory fragmentation and waste.
    • Continuous batching: As soon as a request completes, a new request joins the current batch instead of waiting for the entire batch to finish.

    The gains from these techniques depend on request length distribution and concurrency level. Improvements vary widely across workloads, so rely on your own load tests rather than someone else’s benchmarks.

    Launch example (vLLM):

    1. vllm serve /data/models/your-model \
    2. --tensor-parallel-size 2 \
    3. --max-model-len 8192 \
    4. --gpu-memory-utilization 0.90

    --max-model-len caps the maximum length per request. Setting it too high consumes more GPU memory, so size it to your actual business needs.

    2. Standardize Your Benchmarking

    Benchmark reports must state the test conditions, otherwise numbers cannot be compared. Record the following metrics:

    • Time to First Token (TTFT): From request submission to the first token received.
    • Latency percentiles: Overall response time at P95 and P99.
    • Throughput: Tokens generated per second.
    • Unit cost: GPU-hours per thousand tokens.

    Test conditions should include input length, output length, concurrency level, GPU model, and inference engine version.