본문 바로가기

Engineering

vLLM이란? (2/2)

이번 포스팅은 vLLM의 설치, 사용법, 기능 등 실용적인 내용들을 다룹니다.

vLLM의 원리 등에 대한 이론적 내용들은 이전 포스팅에서 확인하실 수 있습니다.

 

vLLM이란? (1/2)

이번 포스팅은 현재 LLM 서빙 프레임워크의 표준으로 자리잡고 있는 vLLM이라는 오픈소스에 대해 정리합니다.vLLM은 무엇이고, 어떤 장점때문에 인기있는 라이브러리가 되었으며, 그 원리는 무엇

hanarchive.tistory.com

 

본 포스팅의 목차는 다음과 같습니다.

 

1. vLLM 설치 방법

2. vLLM 실행 예제

  2-1) Offline Batched Inference

  2-2) Online Serving using OpenAI-compatiable Server]

* References


1. vLLM 설치 방법 (vLLM installation)

기본적으로 vLLM은 간단하게 다음 명령어로 설치할 수 있다.

pip install vllm

 

단, 다음과 같은 Requirements를 만족해야 한다.

  • OS: Linux
  • Python: 3.10 - 3.13

현 시점에서 Mac os, Window에서는 지원하지 않으며, Window 유저들은 WSL을 사용하면 설치 가능하다.

 

docs에서는 uv를 이용한 가상환경 사용을 권장하고 있으며, 다음과 같이 이용할 수 있다.

uv venv --python 3.12 --seed
source .venv/bin/activate
uv pip install vllm --torch-backend=auto

 

--torch-backend=auto 옵션을 통해 설치된 CUDA driver에 맞는 버전을 편하게 설치할 수 있다.

 

2. vLLM 실행 예제 (Quickstart)

2-1) Offline Batched Inference

오프라인 배치 추론은 미리 정의된 입력 프롬프트 목록에 대해 텍스트를 한 번에 생성하는 것을 의미한다.

간단하게 vllm.LLM, vllm.SamplingParams 클래스를 이용하면 사용 가능하다.

from vllm import LLM, SamplingParams

prompts = [
    "Hello, my name is",
    "The president of the United States is",
    "The capital of France is",
    "The future of AI is",
]
sampling_params = SamplingParams(temperature=0.8, top_p=0.95)

llm = LLM(model="facebook/opt-125m")

 

만일 sampling parameter를 지정하지 않으면 Hugging Face model repository에서 자동으로 generation_config.json을 불러와서 적용을 시도한다.

 

이를 무시하고 default 샘플링값으로 사용하고 싶다면, llm = LLM(model="...", generation_config="vllm") 과 같이 LLM 인스턴스를 초기화하면 된다.

 

sampling parameter를 이러한 LLM 인스턴스의 generate 메서드에 전달할 경우, override되어 인스턴스의 파라미터보다 항상 우선시된다.

outputs = llm.generate(prompts, sampling_params)

for output in outputs:
    prompt = output.prompt
    generated_text = output.outputs[0].text
    print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")

 

output은 RequestOutput 객체이다. 

llm.generate()  은 기본적으로 chat mode를 지원하지 않으며, 이 때에는 llm.chat()을 사용하면 된다.

# Using tokenizer to apply chat template
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("/path/to/chat_model")
messages_list = [
    [{"role": "user", "content": prompt}]
    for prompt in prompts
]
texts = tokenizer.apply_chat_template(
    messages_list,
    tokenize=False,
    add_generation_prompt=True,
)

# Generate outputs
outputs = llm.generate(texts, sampling_params)

# Print the outputs.
for output in outputs:
    prompt = output.prompt
    generated_text = output.outputs[0].text
    print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")

# Using chat interface.
outputs = llm.chat(messages_list, sampling_params)
for idx, output in enumerate(outputs):
    prompt = prompts[idx]
    generated_text = output.outputs[0].text
    print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")

 

2-2) Online Serving using OpenAI-Compatible Server

vLLM의 가장 유용한 기능 중 하나는 OpenAI API protocol와 호환된다는 점이다.

이를 통해 OpenAI API를 사용하는 application과 쉽게 결합될 수 있다.

 

vLLM 서버를 시작하는 방법은 다음과 같다.

vllm serve Qwen/Qwen2.5-1.5B-Instruct

 

이 명령어는 다음과 같은 과정을 수행한다.

  1. 지정된 모델을 다운로드합니다 (이미 캐시되지 않은 경우).
  2. 모델을 GPU에 로드합니다.
  3. 웹 서버를 시작합니다 (기본적으로 Uvicorn 사용).
  4. 들어오는 API 요청을 수신 대기를 합니다. 일반적으로 http://localhost:8000에서 수신 대기합니다.

이 때 --host와 --port로 주소를 설정할 수 있다.

 

이렇게 띄운 vLLM 서버를 Completions API, Chat API 등 다양한 OpenAI-style API로 이용할 수 있다.

OpenAI Completions API with vLLM

구동중인 서버의

v1/completions

엔드포인트에 요청을 날리는 방법이다.

curl http://localhost:8000/v1/completions \
    -H "Content-Type: application/json" \
    -d '{
        "model": "Qwen/Qwen2.5-1.5B-Instruct",
        "prompt": "San Francisco is a",
        "max_tokens": 7,
        "temperature": 0
    }'

 

openai Python 패키지를 사용하는 방법은 다음과 같다.

from openai import OpenAI

# Modify OpenAI's API key and API base to use vLLM's API server.
openai_api_key = "EMPTY"
openai_api_base = "http://localhost:8000/v1"
client = OpenAI(
    api_key=openai_api_key,
    base_url=openai_api_base,
)
completion = client.completions.create(model="Qwen/Qwen2.5-1.5B-Instruct",
                                    prompt="San Francisco is a")
print("Completion result:", completion)

 

OpenAI Chat Completions API with vLLM

Completions API는 주로 레거시 코드에서 많이 사용되며, 현재는 Chat Completions API나 Responses API가 널리 사용되는 추세이다.

Chat Completions API는 'system', 'user' 등 role을 지정할 수도 있고, Function Calling 기능도 제공한다.

 

Chat Completions API의 사용법은 다음과 같다.

curl http://localhost:8000/v1/chat/completions \
    -H "Content-Type: application/json" \
    -d '{
        "model": "Qwen/Qwen2.5-1.5B-Instruct",
        "messages": [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "Who won the world series in 2020?"}
        ]
    }'

 

openai Python 패키지를 사용하는 방법은 다음과 같다.

from openai import OpenAI
# Set OpenAI's API key and API base to use vLLM's API server.
openai_api_key = "EMPTY"
openai_api_base = "http://localhost:8000/v1"

client = OpenAI(
    api_key=openai_api_key,
    base_url=openai_api_base,
)

chat_response = client.chat.completions.create(
    model="Qwen/Qwen2.5-1.5B-Instruct",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Tell me a joke."},
    ]
)
print("Chat response:", chat_response)

 

 

References

더보기

 

'Engineering' 카테고리의 다른 글

LLM 정렬을 위한 강화학습 방법론 (PPO, DPO, GRPO)  (0) 2025.11.16
vLLM이란? (1/2)  (0) 2025.09.21
쿠버네티스 (Kubernetes, K8s)란?  (1) 2025.08.28
GPT-5 Prompting Guide 설명  (0) 2025.08.15