콘텐츠로 이동

Llama-3-8B(챗봇)

개요

이 튜토리얼은 Rebel100™(RBLN-CR13) NPU 1개를 사용하여 HuggingFace의 Llama 3 모델을 컴파일하고 배포하는 방법을 설명합니다. 이 가이드에서는 meta-llama/Meta-Llama-3-8B-Instruct 모델을 사용합니다.

Rebel100™에서 서빙하기

Rebel100™에서는 LLM 서빙에 RBLN vLLM(vllm serve)를 기본으로 사용하는 것을 권장합니다. 모델 컴파일과 OpenAI 호환 API 서빙을 한 번에 처리합니다. 자세한 내용은 Meta-Llama-3-8B-Instruct 레시피에서 확인할 수 있습니다. 이 튜토리얼은 optimum-rbln Python API를 다루며, 컴파일을 확인하거나 추론을 직접 실행할 때 유용합니다.

Note

Rebel100™은 RSD를 지원하지 않으며(버전 매트릭스 참고), Model Zoo의 모든 Rebel100™ 예제가 NPU 1개용으로 컴파일하므로 이 튜토리얼에서도 rbln_num_devices를 1로 설정합니다.

Note

Llama 3는 LLAMA Community License에 따라 제공됩니다. Copyright (c) Meta Platforms, Inc. All Rights Reserved.

환경 설정 및 설치 확인

시작하기 전에 시스템 환경이 올바르게 구성되어 있고 필요한 패키지가 모두 설치되어 있는지 확인합니다. 필요한 항목은 다음과 같습니다:

Note

  • rebel-compiler를 사용하려면 RBLN 포털 계정이 필요합니다.
  • 위 명령은 Debian 계열 Linux(예: Ubuntu)에서 pip로 패키지를 설치하는 일반적인 절차를 전제로 합니다. OS나 환경이 다른 경우에는 설치 가이드에서 지원되는 설치 조합과 적용 가능한 명령을 확인할 수 있습니다.

Note

HuggingFace의 meta-llama/Meta-Llama-3-8B-Instruct 모델은 접근이 제한되어 있습니다. 접근 권한을 부여받은 후, 아래와 같이 hf (huggingface-cli) 명령어를 사용하여 로그인할 수 있습니다:

$ hf auth login

    _|    _|  _|    _|    _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|_|_|_|    _|_|      _|_|_|  _|_|_|_|
    _|    _|  _|    _|  _|        _|          _|    _|_|    _|  _|            _|        _|    _|  _|        _|
    _|_|_|_|  _|    _|  _|  _|_|  _|  _|_|    _|    _|  _|  _|  _|  _|_|      _|_|_|    _|_|_|_|  _|        _|_|_|
    _|    _|  _|    _|  _|    _|  _|    _|    _|    _|    _|_|  _|    _|      _|        _|    _|  _|        _|
    _|    _|    _|_|      _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|        _|    _|    _|_|_|  _|_|_|_|

    To login, `huggingface_hub` requires a token generated from [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) .
Enter your token (input will not be visible):

RBLN Optimum 사용하기

이 단계에서는 Rebel100™ NPU 1개에서 실행되도록 meta-llama/Meta-Llama-3-8B-Instruct 모델을 컴파일합니다.

모델 컴파일

먼저, optimum-rbln에서 RBLNLlamaForCausalLM 클래스를 가져옵니다. 이 클래스의 from_pretrained() 메서드는 HuggingFace 허브에서 Llama 3 모델을 다운로드하고 RBLN SDK를 사용하여 컴파일합니다. 모델을 익스포트할 때 다음 매개변수를 지정합니다:

  • export: 모델을 컴파일하려면 True로 설정해야 합니다.
  • rbln_batch_size: 컴파일을 위한 배치 크기를 정의합니다.
  • rbln_max_seq_len: 최대 시퀀스 길이를 정의합니다.
  • rbln_num_devices: 추론에 사용할 NPU의 수를 정의합니다. Rebel100™에서는 1로 설정합니다.

컴파일 후에는 save_pretrained() 메서드를 사용하여 모델 아티팩트를 디스크에 저장합니다. 이 과정은 컴파일된 모델을 포함하는 디렉터리(예: rbln-Llama-3-8B-Instruct)를 생성합니다.

from optimum.rbln import RBLNLlamaForCausalLM

# Define the HuggingFace model ID
model_id = "meta-llama/Meta-Llama-3-8B-Instruct"

# Compile the model for a single Rebel100™ NPU
compiled_model = RBLNLlamaForCausalLM.from_pretrained(
    model_id=model_id,
    export=True,
    rbln_batch_size=1,
    rbln_max_seq_len=8192,
    rbln_num_devices=1,
)

compiled_model.save_pretrained("rbln-Llama-3-8B-Instruct")

컴파일된 RBLN 모델 불러오기

RBLNLlamaForCausalLM.from_pretrained()를 사용하여 컴파일된 RBLN 모델을 불러옵니다. 저장된 디렉터리 경로를 model_id로 전달하고 export 매개변수를 False로 설정합니다.

1
2
3
4
5
6
7
from optimum.rbln import RBLNLlamaForCausalLM

# Load the compiled RBLN model from the specified directory
compiled_model = RBLNLlamaForCausalLM.from_pretrained(
    model_id="rbln-Llama-3-8B-Instruct",
    export=False
)

입력 준비하기

transformers 라이브러리의 AutoTokenizer를 사용하여 입력 시퀀스를 토큰화합니다. Llama 3와 같은 지시-튜닝(instruction-tuned) 모델에는 채팅 템플릿을 적용합니다.

1
2
3
4
5
6
7
8
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")
tokenizer.pad_token = tokenizer.eos_token

conversation = [{"role": "user", "content": "Hey, are you conscious? Can you talk to me?"}]
text = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False)
inputs = tokenizer(text, return_tensors="pt", padding=True)

모델 추론

이제 generate() 메서드를 사용하여 응답을 생성할 수 있습니다.

1
2
3
4
5
6
7
8
9
output_sequence = compiled_model.generate(
    inputs.input_ids,
    attention_mask=inputs.attention_mask,
    do_sample=False,
    max_length=8192,
)

out = tokenizer.batch_decode(output_sequence, skip_special_tokens=True, clean_up_tokenization_spaces=True)
print(out[0])

예시 출력:

1
2
3
4
5
Hello there! I'm an AI, which means I'm a computer program designed to simulate conversation and answer questions to the best of my ability. I don't have consciousness in the way that humans do, but I'm designed to be very conversational and can understand and respond to language in a way that might seem like I'm conscious.

I can certainly chat with you and answer your questions to the best of my ability. I can provide information on a wide range of topics, from science and history to entertainment and culture. I can also help with tasks like language translation, text summarization, and even generating creative writing.

So, what's on your mind? Is there something specific you'd like to talk about or ask me? I'm all ears (or rather, all text)!

참고