오프라인 배치 추론 (Offline Batched Inference)

오프라인 배치 추론 (Offline Batched Inference)

vLLM이 설치되면, 입력 프롬프트 목록에 대해 텍스트를 생성할 수 있어요. 즉 **오프라인 배치 추론(offline batch inferencing)**을 할 수 있다는 뜻이에요. 예시 스크립트는 examples/basic/offline_inference/basic.py에서 확인할 수 있어요.

이 예시의 첫 줄은 [LLM][vllm.LLM]과 [SamplingParams][vllm.SamplingParams] 클래스를 import 해요.

  • [LLM][vllm.LLM]은 vLLM 엔진으로 오프라인 추론을 실행하는 메인 클래스예요.
  • [SamplingParams][vllm.SamplingParams]는 샘플링 과정의 파라미터를 지정해요.
from vllm import LLM, SamplingParams

다음 부분에서는 텍스트 생성을 위한 입력 프롬프트 목록과 샘플링 파라미터를 정의해요. 샘플링 온도(sampling temperature)0.8로, nucleus sampling 확률(top-p)은 0.95로 설정했어요. 샘플링 파라미터에 대한 더 자세한 내용은 이 문서에서 찾아볼 수 있어요.

!!! important 기본적으로 vLLM은 Hugging Face 모델 저장소에 generation_config.json이 있으면 그 파일을 적용해 모델 제작자가 권장하는 샘플링 파라미터를 사용해요. 대부분의 경우 [SamplingParams][vllm.SamplingParams]를 지정하지 않으면 기본값으로 최상의 결과를 얻을 수 있어요.

다만 vLLM 자체의 기본 샘플링 파라미터를 쓰고 싶다면, [LLM][vllm.LLM] 인스턴스를 만들 때 `generation_config="vllm"`으로 설정하면 돼요.
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][vllm.LLM] 클래스는 vLLM의 엔진과 OPT-125M 모델을 초기화해 오프라인 추론을 준비해요. 지원되는 모델 목록은 여기에서 확인할 수 있어요.

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

!!! note 기본적으로 vLLM은 Hugging Face에서 모델을 다운로드해요. ModelScope에서 모델을 쓰고 싶다면, 엔진을 초기화하기 전에 환경 변수 VLLM_USE_MODELSCOPE를 설정하세요.

```shell
export VLLM_USE_MODELSCOPE=True
```

이제부터가 재미있는 부분이에요! 출력은 llm.generate를 사용해 생성돼요. 이 메서드는 입력 프롬프트를 vLLM 엔진의 **대기 큐(waiting queue)**에 추가하고, 엔진을 실행해 **높은 처리량(high throughput)**으로 출력을 생성해요. 출력은 모든 출력 토큰을 담고 있는 RequestOutput 객체의 리스트로 반환돼요.

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}")

!!! note llm.generate 메서드는 입력 프롬프트에 모델의 채팅 템플릿을 자동으로 적용하지 않아요. 따라서 Instruct 모델이나 Chat 모델을 쓴다면, 기대하는 동작을 위해 해당 채팅 템플릿을 수동으로 적용해야 해요. 또는 llm.chat 메서드를 사용해 OpenAI의 client.chat.completions에 전달하는 것과 같은 형식의 메시지 리스트를 넘길 수도 있어요.

??? code

    ```python
    # 토크나이저를 사용해 채팅 템플릿 적용
    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,
    )
    
    # 출력 생성
    outputs = llm.generate(texts, 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}")

    # 채팅 인터페이스 사용
    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}")
    ```