This document is relevant for: Trn2, Trn3

Tutorial: Serve multiple LoRA adapters with vLLM Neuron using Llama 3.1 8B#

This tutorial shows how to serve two LoRA adapters on one Llama 3.1 8B base model with vLLM on Neuron. When you complete it, you can send a request to the base model or to an adapter, and mix them in one batch.

Overview#

A LoRA adapter is a small set of low-rank weights that changes the behavior of a base model. Multi-LoRA serving keeps one copy of the base model on the device and serves several adapters with it. Each request selects the base model or one adapter.

vLLM Neuron keeps the LoRA weights in a fixed number of adapter slots in device memory (HBM). Slot 0 holds zeros and serves the base model. The slot weights are inputs of the compiled graphs, so a new adapter does not cause a recompile. The decode kernels select the slot of each token, so one decode batch can mix base-model requests and requests for different adapters.

vLLM Neuron uses the standard vLLM LoRA arguments: --enable-lora, --max-loras, --max-lora-rank, and --lora-modules. The server loads each --lora-modules adapter into a slot at startup. An offline LoRARequest loads its adapter when a request uses it for the first time.

In this tutorial, you do these steps:

  1. Download the base model and two public adapters.

  2. Run offline inference with the base model and with each adapter.

  3. Start an OpenAI-compatible server with the two adapters.

  4. Select an adapter for each request.

  5. Send base and adapter requests at the same time.

Before you start#

This tutorial assumes that you have experience in these areas:

  • Running a vLLM Neuron server. See the online serving quickstart.

  • Working with Hugging Face models and access tokens.

  • The basic concepts of LoRA fine-tuning.

Model details#

This tutorial uses these models and settings:

Limitations:

  • On Llama, multi-LoRA supports BF16 weights with BF16 LoRA weights only.

  • Multi-LoRA rejects speculative decoding, jump-forward decoding, decode-context parallelism, attention data parallelism, MLP data parallelism, and pooling models at startup.

  • This tutorial disables prefix caching. Prefix caching with LoRA needs segmented prefill. See the compatibility matrix in the features guide.

For the full list, see Multi-LoRA in the features guide.

Prerequisites#


Prepare your environment#

Set your Hugging Face access token in the shell that you use for this tutorial.

export HF_TOKEN=hf_XXXXXXXXXXXXXXXXXXXXXXXXXXXX

Step 1: Download the base model and the adapters#

In this step, you download the base model and the two adapters to local directories.

hf download meta-llama/Llama-3.1-8B --local-dir ~/models/Llama-3.1-8B
hf download te4bag/LoRA-llama-3.1-8B-gsm8k --local-dir ~/adapters/gsm8k
hf download llama-duo/llama3.1-8b-coding-gpt4o-100k --local-dir ~/adapters/coding

Each adapter directory must be a PEFT adapter. It contains adapter_config.json and adapter_model.safetensors (or adapter_model.bin).

You can also give a Hugging Face Hub repo ID in place of a local directory. Local directories are faster, because vLLM Neuron resolves the path again each time that it loads an evicted adapter.

Step 2: Run offline inference#

In this step, you generate text with the base model and with each adapter, in one LLM instance.

Save this script as multi_lora_offline.py:

import os

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

home = os.path.expanduser("~")

llm = LLM(
    model=f"{home}/models/Llama-3.1-8B",
    tensor_parallel_size=32,
    max_model_len=2048,
    max_num_seqs=4,
    enable_prefix_caching=False,
    enable_lora=True,
    max_loras=2,  # Adapter slots in HBM.
    max_lora_rank=32,  # Equal to or larger than the rank of each adapter.
)

params = SamplingParams(temperature=0.0, max_tokens=128)
math_prompt = (
    "Question: Natalia sold clips to 48 of her friends in April, and then she "
    "sold half as many clips in May. How many clips did Natalia sell altogether "
    "in April and May?\nAnswer:"
)
code_prompt = "Write a Python function that returns the factorial of n."

# Give each adapter its own integer ID, and use it in all requests.
gsm8k = LoRARequest("gsm8k", 1, f"{home}/adapters/gsm8k")
coding = LoRARequest("coding", 2, f"{home}/adapters/coding")

# A request without lora_request uses the base model (slot 0).
base = llm.generate([math_prompt], params)

# One generate() call can use a different adapter for each prompt.
lora = llm.generate([math_prompt, code_prompt], params, lora_request=[gsm8k, coding])

print("Base:\n", base[0].outputs[0].text)
print("Adapter gsm8k:\n", lora[0].outputs[0].text)
print("Adapter coding:\n", lora[1].outputs[0].text)

Run the script:

python multi_lora_offline.py

The first run compiles the model graphs. This can take some minutes. When the model loads, the log shows a line like this:

Multi-LoRA enabled: slots=2, max_lora_rank=32, target_modules=[...], dtype=torch.bfloat16.

The base output and the gsm8k output for the same prompt are different, because the adapter changes the model.

Step 3: Start an online server#

In this step, you start an OpenAI-compatible server that serves the base model and the two adapters.

vllm serve ~/models/Llama-3.1-8B \
  --tensor-parallel-size 32 \
  --max-model-len 2048 \
  --max-num-seqs 4 \
  --no-enable-prefix-caching \
  --enable-lora \
  --max-loras 2 \
  --max-lora-rank 32 \
  --lora-modules gsm8k=$HOME/adapters/gsm8k coding=$HOME/adapters/coding

vLLM accepts only these values for --max-lora-rank: 1, 8, 16, 32, 64, 128, 256, 320, and 512.

Wait until the server log shows Application startup complete.

Step 4: Select an adapter for each request#

In this step, you send requests to each adapter and to the base model.

List the models that the server serves. The list includes the base model and each adapter in --lora-modules.

curl -s localhost:8000/v1/models

To use an adapter, set model to the adapter name:

curl -s localhost:8000/v1/completions -H 'Content-Type: application/json' \
  -d '{"model": "gsm8k", "prompt": "Question: What is 2 + 3 * 4?\nAnswer:", "max_tokens": 64, "temperature": 0}'
curl -s localhost:8000/v1/completions -H 'Content-Type: application/json' \
  -d '{"model": "coding", "prompt": "Write a Python function that returns the factorial of n.", "max_tokens": 128, "temperature": 0}'

To use the base model, set model to the base model name. Without --served-model-name, the base model name is the path that you gave to vllm serve:

curl -s localhost:8000/v1/completions -H 'Content-Type: application/json' \
  -d "{\"model\": \"$HOME/models/Llama-3.1-8B\", \"prompt\": \"Question: What is 2 + 3 * 4?\nAnswer:\", \"max_tokens\": 64, \"temperature\": 0}"

Step 5: Mix the base model and the adapters in one batch#

In this step, you send base and adapter requests at the same time. The server puts them in the same decode batch.

for model in gsm8k coding "$HOME/models/Llama-3.1-8B"; do
  curl -s localhost:8000/v1/completions -H 'Content-Type: application/json' \
    -d "{\"model\": \"$model\", \"prompt\": \"Question: What is 7 * 8?\nAnswer:\", \"max_tokens\": 64, \"temperature\": 0}" &
done
wait

Each adapter request gets the output of the adapter. Each base request gets the output of the base model. The decode kernels select the adapter of each sequence in the batch.

To serve more adapters, add each adapter to --lora-modules, or load it at runtime with /v1/load_lora_adapter. --max-loras sets the number of different adapters that one batch can use. A request for another adapter waits until a slot is free.

All complete! Now, confirm that everything works.

Confirmation#

You now serve the base model and two LoRA adapters from one vLLM Neuron server. Check these items:

  • The log shows Multi-LoRA enabled: slots=2, max_lora_rank=32, ....

  • /v1/models lists gsm8k and coding.

  • A request to an adapter gives a different output than the same request to the base model.

If you have a problem, see the “Common issues” section.


Common issues#

  • <Model> does not support LoRA yet.: The model does not declare SupportsLoRA. Use a Llama model, or add LoRA support to your model. See Add LoRA to a custom model.

  • Multi-LoRA on Llama supports only an unquantized bfloat16 model with bfloat16 LoRA weights: Use an unquantized BF16 checkpoint with --dtype bfloat16, and keep --lora-dtype at auto or bfloat16.

  • Multi-LoRA on Neuron does not support: ...: The message lists each unsupported item, for example speculative decoding. Remove each item that the message lists.

  • Adapter rank <r> is larger than --max-lora-rank <n>: Increase --max-lora-rank, or use an adapter with a smaller rank.

  • LoRA adapter <dir> uses PEFT settings that Neuron does not support: The adapter uses DoRA (use_dora), rank_pattern, alpha_pattern, modules_to_save, or a LoRA bias. vLLM Neuron cannot load these adapters.

  • Loading lora <name> failed: No adapter found for <path>: The path in --lora-modules or in the LoRARequest is not an adapter directory, and vLLM cannot resolve it as a Hugging Face Hub repo ID. Give the directory that holds adapter_config.json.

  • --lora-target-modules has '<name>', which is not a LoRA module: Use a name from the list in the message, or remove --lora-target-modules to use all the LoRA modules.

Clean up#

Stop the server with Ctrl+C. vLLM Neuron copies adapter files to /dev/shm/vllm_neuron_lora_cache_<uid>. To release this host memory, remove the directory:

rm -rf /dev/shm/vllm_neuron_lora_cache_$(id -u)

Next steps#

This document is relevant for: Trn2, Trn3