Hugging face Transformer(허깅페이스 트랜스포머) 기초

잭잭·2025년 3월 7일
post-thumbnail

안녕하세요!

오늘은 GSM8K(초등 수학 데이터셋)에 대한 SLM(Small LLM)의 인퍼런스 성능이 궁금해서 허깅페이스에서 돌려보고자 했습니다.

1. 코드 분석

우선 코드는 아래와 같습니다.
허깅페이스에서 그냥 'llama2-7b gsm8k' 검색했고, 가장 먼저 나오는거 골랐어요.
(링크: https://huggingface.co/neuralmagic/Llama-2-7b-gsm8k)

from transformers import AutoTokenizer, AutoModelForCausalLM

tokenizer = AutoTokenizer.from_pretrained("neuralmagic/Llama-2-7b-gsm8k")
model = AutoModelForCausalLM.from_pretrained("neuralmagic/Llama-2-7b-gsm8k", device_map="auto")

input_text = "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?"
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")

outputs = model.generate(**input_ids)
print(tokenizer.decode(outputs[0]))

코드를 한줄씩 뜯어보겠습니다.

1.1 Import

from transformers import AutoTokenizer, AutoModelForCausalLM

트랜스포머 라이브러리부터 토크나이저와 CLM(Casual Language Model)을 불러오고 있네요.

라이브러리와 패키지, 모듈의 개념이 헷갈릴 수 있는데요.
여기서 transformers는 라이브러리이자 패키지, AutoTokenizerAutoModelForCausalLM은 모듈이라고 볼 수 있습니다.
(라이브러리 >= 패키지 >= 모듈)
쉽게 보자면 transformer.py에서 두 AutoTokenizer와 AutoModelForCausalLM라는 클래스가 정의된 형태라고 볼 수 있겠네요.

관련 내용이 더 궁금하시면 https://aliencoder.tistory.com/20 를 참고하세요 :)

1.2 Tokenizer, Model 선언

tokenizer = AutoTokenizer.from_pretrained("neuralmagic/Llama-2-7b-gsm8k")
model = AutoModelForCausalLM.from_pretrained("neuralmagic/Llama-2-7b-gsm8k", device_map="auto")

보통 트랜스포머에서 LLM 을 돌리려면,

  • 토크나이저(Tokenizer)와
  • 모델(model)

을 선언합니다.

1.2.1 AutoTokenizer

1.2.1.1 from_pretrained

위 코드의 경우 tokenizer와 model 모두 pretrain된 것을 가져오고 있습니다. 제가 따로 학습시키거나 파인튜닝하는것이 아니라, 인퍼런스만 돌릴 목적이기 때문이죠!

1.2.1.2 "neuralmagic/Llama-2-7b-gsm8k"

이 위치는 제가 가져오려는 모델의 허깅페이스 주소를 의미합니다. 제가 해당 코드를 https://huggingface.co/neuralmagic/Llama-2-7b-gsm8k
여기서 가져왔죠? 뒤에 보시면 주소가 같은것을 확인하실 수 있습니다.

1.2.2 AutoModelForCausalLM

"neuralmagic/Llama-2-7b-gsm8k" 모델을 Causal Language Model (CLM) 형식으로 불러 오는데요.

Q. Causal Language Model (CLM)이란?
A. Causal Language Model (CLM)은 이전 토큰들만을 참고하여 다음 토큰을 예측하는 모델로, 한 방향(Left-to-Right)으로만 예측 가능하다.입력된 텍스트의 이전 단어(과거 정보)만을 사용하여 다음 단어를 생성한다.

대표적인 CLM 모델은 GPT 시리즈(GPT-2, GPT-3, GPT-4)와 LLaMA 시리즈가 있습니다. 저의 경우 Llama2를 사용하기 때문에 CLM을 호출합니다.

1.2.2.1 device_map="auto"

모델이 자동으로 CPU/GPU를 감지하여 적절한 디바이스에 로드됨

1.3 input_text

input_text = "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?"

input text로, GSM8K 데이터셋 중 예시를 입력합니다.

1.4 input_ids

input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")

input_ids에서 ids는 identifiers의 약자입니다.

즉, input_ids는 토큰(token)의 고유한 식별자(identifier)들의 리스트를 의미합니다.
예를 들어, "Hello world"라는 문장을 토크나이징하면

{
  'input_ids': tensor([[  121,  3204]])
}

와 같이 나올 수 있습니다.

그리고

decoded_text = tokenizer.decode(input_ids['input_ids'][0])
print(decoded_text)

해당 ids를 디코딩 하면, 다시 Hello world가 프린트 되는거죠.

1.5 outputs

outputs = model.generate(**input_ids)

위에서 tokenizer로 변환한 입력의 input_ids 값을 입력받아 모델이 후속 답변을 생성하는 코드입니다.

여기서 **input_ids의 **는 파라미터 언패킹 (unpacking)을 수행하는 역할을 합니다.

📌 언패킹이란?
'input_ids': tensor([[ 121, 3204]])를 예시로 들면, input_ids 딕셔너리의 키-밸류(key-value)값인 121, 3204를 개별 인자로 전달하는것을 말합니다.

1.6 print

print(tokenizer.decode(outputs[0]))

토크나이저를 통해, 모델이 생성한 output(출력 ids값)을 자연어로 디코딩 하는 과정입니다.

2. 출력 결과

<s> 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?<s> Natalia sold 48/2 = <<48/2=24>>24 clips in May.
She sold 48 + 24 = <<48+24=72>>72 clips altogether in April and May.
#### 72</s>

다음과 같이 출력해주고 있네요!
정답만 출력하는 것이 아닌 중간 추론 과정까지 출력하고 있는데요.
아마 그 이유는, 이 llama2-7b 모델이 GSM8K 데이터셋으로 파인튜닝 되었고
GSM8K는 초등 수학 문제와, 추론 과정, 답변을 포함하고 있기 때문입니다.

오늘 글 어떠셨나요?
수정할 부분이나, 더 알고싶으신 부분 댓글로 남겨주시면 감사하겠습니다.

profile
대학원 지망생 (인턴)

0개의 댓글