Llama3-8B 모델 적용하기(챗봇)
이 튜토리얼은 여러 대의 RBLN NPU들을 사용하여 Meta의 최신 모델인 Llama3 모델을 컴파일하고 배포하는 방법을 소개합니다. 이 듀토리얼에서는 허깅페이스에 올라와있는 meta-llama/Meta-Llama-3-8B-Instruct 모델을 사용합니다.
이 튜토리얼은 두 단계로 구성되어 있습니다:
- Llama3-8B 모델을 여러 개의 RBLN NPU를 대상으로 컴파일하고 컴파일된 모델을 저장하는 방법.
- 컴파일된 모델을 런타임 기반 추론 환경에서 배포하는 방법.
Note
다중 NPU 기능은 ATOM+(RBLN-CA12
)에서만 지원됩니다. 지금 사용 중인 NPU의 종류는 rbln-stat
명령어로 확인할 수 있습니다.
사전준비
Llama3-8B 모델을 효율적으로 컴파일하고 배포하려면 4개의 RBLN NPU(ATOM+, RBLN-CA12
)를 사용해야 합니다. 모델을 실행하는 데 필요한 NPU 개수 및 다중 NPU에 대한 자세한 내용은 optimum-rbln 문서에서 확인할 수 있습니다.
시작하기 전에 다음의 파이썬 패키지들이 시스템에 설치되어 있는지 확인하세요:
허깅페이스 meta-llama/Meta-Llama-3-8B-Instruct 모델은 접근이 제한되어 있습니다. 접근 권한을 얻기 위해서는 라이선스를 승인하고 모델 카드에서 접근 권한을 얻기 위한 서류를 작성해야 합니다. 접근 권한이 부여되면 아래와 같이 huggingface-cli 커맨드를 통해 모델에 접근할 수 있습니다:
| $ huggingface-cli login
_| _| _| _| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _|_|_|_| _|_| _|_|_| _|_|_|_|
_| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|
_|_|_|_| _| _| _| _|_| _| _|_| _| _| _| _| _| _|_| _|_|_| _|_|_|_| _| _|_|_|
_| _| _| _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|
_| _| _|_| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _| _| _| _|_|_| _|_|_|_|
To login, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens .
Token: *****
|
Note
모델을 RBLN NPU에서 빠르게 컴파일하고 배포하는 자세한 내용을 생략하고 싶다면, 이 튜토리얼의 요약 섹션으로 바로 이동해서 확인할 수 있습니다. 해당 섹션에서는 모델을 컴파일하고 배포하는 모든 단계를 포함하고 있어, 본인만의 프로젝트를 빠르게 시작할 수 있습니다.
1단계. 모델 컴파일하기
4개의 RBLN NPU를 사용하여 허깅페이스 Llama3-8B 모델을 컴파일합니다.
다중 NPU 컴파일
먼저 optimum-rbln 라이브러리에서 RBLNLlamaForCausalLM
클래스를 가져옵니다. 이 클래스는 RBLNLlamaForCausalLM.from_pretrained()
메서드를 제공하며, 이는 허깅페이스 허브에서 Llama3 모델을 다운로드하고 RBLN SDK를 이용하여 컴파일합니다. 이 메서드를 사용할 때 다음 매개변수를 입력해야합니다:
export
: True로 설정되어야 RBLN SDK를 이용하여 모델을 컴파일 합니다. False로 설정할 경우 사전컴파일된 모델을 로드하게 됩니다.
rbln_batch_size
: 배치 크기를 정의합니다.
rbln_max_seq_len
: 최대 문자열 길이 정의합니다.
rbln_tensor_parallel_size
: 추론에 사용할 NPU 개수를 설정합니다.
| from optimum.rbln import RBLNLlamaForCausalLM
model_id = "meta-llama/Meta-Llama-3-8B-Instruct"
compiled_model = RBLNLlamaForCausalLM.from_pretrained(
model_id=model_id,
export=True,
rbln_batch_size=1,
rbln_max_seq_len=8192,
rbln_tensor_parallel_size=4, # 4개의 RBLN NPU 디바이스 대상으로 컴파일
)
|
컴파일한 모델 저장
모델을 컴파일한 후 , compiled_model.generate()
메서드를 사용하여 직접 텍스트를 생성할 수 있습니다. 또한, compiled_model.save_pretrained()
메서드를 사용하여 컴파일된 모델을 디스크에 저장할 수 있습니다
| compiled_model.save_pretrained("rbln-Llama-3-8B-Instruct")
|
2단계. 모델 배포하기
이 섹션에서는 컴파일된 모델을 로드하여 텍스트를 생성하는 방법을 소개합니다.
컴파일된 RBLN 모델 로드
먼저 RBLNLlamaForCausalLM.from_pretrained()
메서드를 사용하여 컴파일된 RBLN 모델을 로드할 수 있습니다. 컴파일된 모델의 경로
를 인수로 전달하고, export
매개변수를 False로 설정하세요.
| from optimum.rbln import RBLNLlamaForCausalLM
compiled_model = RBLNLlamaForCausalLM.from_pretrained(
model_id="rbln-Llama-3-8B-Instruct",
export=False
)
|
입력 데이터 준비
트랜스포머 라이브러리에서 제공하는 AutoTokenizer
를 사용하여 입력문자열을 토큰화하고 사전처리 과정을 수행합니다.
| 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()
메서드를 사용하여 텍스트를 생성할 수 있습니다.
| 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])
|
아래와 유사한 내용의 텍스트가 생성됩니다.
| Hello! 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 responsive and interactive.
I can understand and respond to language, and I can even learn and improve over time based on the conversations I have with users like you. So, in a sense, I'm "awake" and ready to chat with you!
What would you like to talk about? Do you have a specific question or topic in mind, or do you just want to chat about something random? I'm here to listen and help if I can!
|
요약
허깅페이스 Llama3-8B
모델을 컴파일하는 코드는 아래와 같습니다:
| # 모델을 컴파일하고 내보내기
from optimum.rbln import RBLNLlamaForCausalLM
model_id = "meta-llama/Meta-Llama-3-8B-Instruct"
model_save_dir = "rbln-Llama-3-8B-Instruct"
compiled_model = RBLNLlamaForCausalLM.from_pretrained(
model_id=model_id,
export=True,
rbln_batch_size=1,
rbln_max_seq_len=8192,
rbln_tensor_parallel_size=4, # 4개의 RBLN NPU 디바이스 대상으로 컴파일
)
# 컴파일된 모델을 디스크에 저장
compiled_model.save_pretrained(model_save_dir)
|
컴파일된 `Llama3-8B' 모델의 문장 생성을 위한 코드는 아래와 같습니다:
| from transformers import AutoTokenizer
from optimum.rbln import RBLNLlamaForCausalLM
# 컴파일된 모델 로드
compiled_model = RBLNLlamaForCausalLM.from_pretrained(
model_id="rbln-Llama-3-8B-Instruct",
export=False,
)
# input 준비
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)
# 일련의 token id 생성
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])
|