Skip to content

Advanced

Local Weight Deployment

When you download weights from PyTRIO, the archive contains a standard PEFT LoRA adapter rather than a full copy of the model. To run inference locally, pair the adapter with its matching base model using one of the following options:

Deployment OptionMerge RequiredBest For
Transformers + PEFTNoQuick verification, local debugging, single or small-batch inference
vLLM with dynamic LoRANoHigh-throughput serving, offline batch evaluation, serving multiple LoRAs on one base model
Merged weights (vLLM / Transformers)YesZero LoRA runtime overhead, exporting a standalone Hugging Face model for any inference engine

Prerequisites ​

1. Extract the Downloaded Archive ​

Extract the .zip archive into ./checkpoint:

bash
unzip YOUR_CHECKPOINT_ID.zip -d ./checkpoint

The extracted directory contains:

text
checkpoint/
├── adapter_config.json         # LoRA config (r, lora_alpha, target_modules, etc.)
├── adapter_model.safetensors   # LoRA adapter weights
└── generation_config.json      # Generation parameters

TIP

Check r (LoRA rank) and base_model_name_or_path in checkpoint/adapter_config.json. When loading the adapter directly in vLLM, make sure --max-lora-rank is greater than or equal to r.

2. Download the Matching Base Model ​

The examples below use Qwen/Qwen3.5-4B. Replace it with the exact base_model used during training.

Using Hugging Face:

bash
pip install huggingface_hub
huggingface-cli download Qwen/Qwen3.5-4B --local-dir ./base_model

Or using ModelScope (recommended for mainland China networks):

bash
pip install modelscope
python -c "from modelscope import snapshot_download; snapshot_download('Qwen/Qwen3.5-4B', local_dir='./base_model')"

Deploy with Transformers ​

Install the required packages:

bash
pip install transformers peft accelerate torch

Attach the downloaded adapter to the base model with peft without merging weights:

python
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer

BASE_MODEL_PATH = "./base_model"
ADAPTER_PATH = "./checkpoint"

tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_PATH, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    BASE_MODEL_PATH,
    dtype=torch.bfloat16,
    device_map="auto",
    trust_remote_code=True,
)

# Attach the LoRA adapter downloaded from PyTRIO
model = PeftModel.from_pretrained(model, ADAPTER_PATH)  
model.eval()

messages = [{"role": "user", "content": "Hello, please introduce yourself."}]
text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
)
inputs = tokenizer([text], return_tensors="pt").to(model.device)

with torch.no_grad():
    output_ids = model.generate(
        **inputs,
        max_new_tokens=512,
        temperature=0.7,
        top_p=0.8,
        do_sample=True,
    )

new_ids = output_ids[0][inputs["input_ids"].shape[1]:]
print(tokenizer.decode(new_ids, skip_special_tokens=True))

Option 2: Merge LoRA and Load Full Weights ​

To bake the LoRA weights into the base model and produce a standalone Hugging Face model (no peft dependency at inference time, and compatible with vLLM, SGLang, Ollama, etc.), run a merge script first:

python
# merge_lora.py
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer

BASE_MODEL_PATH = "./base_model"
ADAPTER_PATH = "./checkpoint"
MERGED_PATH = "./merged_model"

tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_PATH, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    BASE_MODEL_PATH,
    dtype=torch.bfloat16,
    device_map="cpu",  # Merge on CPU to save GPU memory
    trust_remote_code=True,
)

model = PeftModel.from_pretrained(model, ADAPTER_PATH)
model = model.merge_and_unload()  

model.save_pretrained(MERGED_PATH, safe_serialization=True)
tokenizer.save_pretrained(MERGED_PATH)
print(f"Merged model saved to {MERGED_PATH}")

Run the merge script:

bash
python merge_lora.py

You can then load ./merged_model directly with transformers:

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

MERGED_PATH = "./merged_model"

tokenizer = AutoTokenizer.from_pretrained(MERGED_PATH, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    MERGED_PATH,
    dtype=torch.bfloat16,
    device_map="auto",
    trust_remote_code=True,
)
model.eval()

messages = [{"role": "user", "content": "Hello, please introduce yourself."}]
text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
)
inputs = tokenizer([text], return_tensors="pt").to(model.device)

with torch.no_grad():
    output_ids = model.generate(
        **inputs,
        max_new_tokens=512,
        temperature=0.7,
        top_p=0.8,
        do_sample=True,
    )

new_ids = output_ids[0][inputs["input_ids"].shape[1]:]
print(tokenizer.decode(new_ids, skip_special_tokens=True))

Deploy with vLLM ​

Install vLLM:

bash
pip install vllm

vLLM supports both dynamic LoRA loading and serving merged full weights.

Option 1: Load the LoRA Adapter Directly (No Merge Required) ​

1. Start an OpenAI-Compatible API Server ​

Launch vllm serve with --enable-lora and --lora-modules pointing to your extracted adapter directory:

bash
vllm serve ./base_model \
  --enable-lora \
  --lora-modules my-lora=./checkpoint \
  --max-lora-rank 32 \
  --dtype bfloat16 \
  --port 8000

WARNING

vLLM defaults to --max-lora-rank 16, whereas PyTRIO runs often use rank=32 or higher. Check r in checkpoint/adapter_config.json and set --max-lora-rank to at least that value, or vLLM will fail to load the adapter.

To serve multiple LoRA adapters on top of the same base model, list them separated by spaces in --lora-modules:

bash
vllm serve ./base_model \
  --enable-lora \
  --lora-modules lora-v1=./checkpoint_v1 lora-v2=./checkpoint_v2 \
  --max-lora-rank 32 \
  --dtype bfloat16 \
  --port 8000

Once the server is running, call it with any OpenAI-compatible client by setting model to the adapter name (for example, my-lora):

python
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY",
)

response = client.chat.completions.create(
    model="my-lora",  # Must match the name in --lora-modules  #
    messages=[{"role": "user", "content": "Hello, please introduce yourself."}],
    max_tokens=512,
    temperature=0.7,
    top_p=0.8,
)

print(response.choices[0].message.content)

Or test it with curl:

bash
curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "my-lora",
    "messages": [{"role": "user", "content": "Hello, please introduce yourself."}],
    "max_tokens": 512,
    "temperature": 0.7,
    "top_p": 0.8
  }'

2. Offline Batch Inference in Python ​

For offline evaluation or batch generation in Python, use vllm.LLM together with LoRARequest:

python
from vllm import LLM, SamplingParams
from vllm.lora.request import LoRARequest

llm = LLM(
    model="./base_model",
    enable_lora=True,
    max_lora_rank=32,  # Must be >= r in adapter_config.json  #
    dtype="bfloat16",
)

sampling_params = SamplingParams(
    temperature=0.7,
    top_p=0.8,
    max_tokens=512,
)

lora_request = LoRARequest(
    lora_name="my-lora",
    lora_int_id=1,
    lora_path="./checkpoint",  
)

conversations = [
    [{"role": "user", "content": "Hello, please introduce yourself."}],
    [{"role": "user", "content": "Summarize LoRA fine-tuning in three sentences."}],
]

outputs = llm.chat(
    messages=conversations,
    sampling_params=sampling_params,
    lora_request=lora_request,
)

for output in outputs:
    print(output.outputs[0].text)
    print("-" * 40)

Option 2: Deploy Merged Full Weights ​

If you already merged the adapter into ./merged_model with merge_lora.py, serve it directly as a standard Hugging Face model. This removes LoRA runtime overhead and works seamlessly with quantization and other vLLM optimizations.

1. Start an OpenAI-Compatible API Server ​

bash
vllm serve ./merged_model \
  --served-model-name my-model \
  --dtype bfloat16 \
  --port 8000

Send requests with model="my-model":

python
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY",
)

response = client.chat.completions.create(
    model="my-model",
    messages=[{"role": "user", "content": "Hello, please introduce yourself."}],
    max_tokens=512,
    temperature=0.7,
    top_p=0.8,
)

print(response.choices[0].message.content)

2. Offline Batch Inference in Python ​

python
from vllm import LLM, SamplingParams

llm = LLM(
    model="./merged_model",
    dtype="bfloat16",
)

sampling_params = SamplingParams(
    temperature=0.7,
    top_p=0.8,
    max_tokens=512,
)

conversations = [
    [{"role": "user", "content": "Hello, please introduce yourself."}],
]

outputs = llm.chat(
    messages=conversations,
    sampling_params=sampling_params,
)

print(outputs[0].outputs[0].text)

Notes ​

  • Exact base model match required: Always pair the LoRA adapter with the exact base_model used for training; using a different model version will cause shape mismatches or corrupted outputs.
  • Sampler checkpoints only: Only Sampler checkpoints saved via save_weights_for_sampler can be downloaded and deployed. If you only have a Train checkpoint, follow Convert Train Weights to Sampler first and then Download Adapters.
  • Multi-GPU and memory settings: Use device_map="auto" in Transformers to shard across GPUs. In vLLM, pass --tensor-parallel-size N for tensor parallelism, and lower --gpu-memory-utilization or --max-model-len if GPU memory is constrained.
  • Multimodal models: If you fine-tuned a vision-language model and want to pass images locally, use the corresponding multimodal model class with AutoProcessor in Transformers, or send OpenAI-compatible image_url message payloads in vLLM.