Prompt Engineering 실습 1
- LLaMA-3-8B (Multi-turn PE, Few-shot PE)
- Mistral-7B (CoT PE, Zero-shot PE)
- Phi-3-3.8B (Multi-turn PE, Generated Knowledge PE)
- Gemma 7B (Few-shot PE, Self-Ask PE, Chaining)
Contents
- 모델 설정
- Multi-Turn PE
- Zero-Shot PE
- Few-Shot PE
관련 패키지 설치 및 환경 설정
!pip install bitsandbytes==0.43.1
!pip install accelerate==0.30.1
!pip install transformers==4.39.3
!pip install gradio==4.29.0
1. 모델 설정
import torch
from transformers import (
AutoTokenizer,
AutoModelForCausalLM,
BitsAndBytesConfig
)
a) 모델 설정: LLaMA-3-8B
model_id = "meta-llama/Meta-Llama-3-8B-Instruct"
b) Tokenizer 불러오기
tokenizer = AutoTokenizer.from_pretrained(model_id)
c) Model 불러오기
Quantization 설정
config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.bfloat16
)
(Quantize해서) 불러오기
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.bfloat16,
device_map="auto",
quantization_config=config
)
2. Multi-Turn PE
a) Prompt (message)
- Multi-Turn PE에 맞는 prompt 구성하기
messages = [
{"role": "system", "content": "You are a nice chatbot that helps users. You always have to respond briefly, within three sentences."},
{"role": "user", "content": "What is the capital of the United States?"},
{"role": "assistant", "content": "The capital of the United States is Washington D.C."},
{"role": "user", "content": "Then, what about Korea?"}
]
b) Tokenize
input_ids = tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
return_tensors="pt"
).to(model.device)
Note: Terminator는 LLaMA 계열의 모델에만 필요하다!
terminators = [
tokenizer.eos_token_id,
tokenizer.convert_tokens_to_ids("<|eot_id|>")
]
c) Generate
outputs = model.generate(
input_ids,
max_new_tokens=512,
eos_token_id=terminators,
do_sample=True,
temperature=0.6,
top_p=0.9,
)
d) Result
response = outputs[0][input_ids.shape[-1]:]
print("response : ", tokenizer.decode(response, skip_special_tokens=True))
The capital of South Korea is Seoul, and the capital of North Korea is Pyongyang.
3. Zero-Shot PE
a) Prompt (message)
- Zero-shot PE에 맞는 prompt 구성하기
messages = [
{
"role": "system",
"content": "You are a Korea robot that summarizes documents. You MUST answer in Korea"
},
{
"role": "user",
"content": """
###document: 기후 변화는 수십 년에서 수백만 년에 걸친 기간 동안의 기상 패턴의 통계적 분포에서 장기적인 변화를 의미합니다.
이는 평균 기상 조건의 변화, 또는 평균 조건 주변의 기상 분포의 변화를 의미할 수 있습니다.
또한 이것은 기온, 강수량, 또는 바람 패턴의 변화를 포함할 수 있습니다.
"""
}
]
for message in messages:
message["content"] = message["content"].replace("\n", "")
b) Tokenize
위와 동일
c) Generate
위와 동일
d) Result
위와 동일
4. Few-Shot PE
a) Prompt (message)
- Few-shot PE에 맞는 prompt 구성하기
messages = [
{"role": "system", "content": "You are a korea robot that summarizes documents. You MUST answer in Korea"},
{"role": "user", "content": """
###document: 에펠탑은 프랑스 파리의 샹 드 마르스에 위치한 철제 격자 탑입니다.
이 탑은 그것을 설계하고 건설한 회사의 엔지니어인 구스타브 에펠타의 이름을 딴 것입니다.
1887년부터 1889년까지 1889년 세계 박람회의 입구로 건설되었으며,
처음에는 그 디자인을 이유로 프랑스의 주요 예술가들과 지식인들로부터 비판을 받았습니다.
하지만 이제는 프랑스의 전세계적인 문화 아이콘 그리고 세계에서 가장 알아보기 쉬운 구조물 중 하나가 되었습니다.
"""},
{"role": "assistant", "content": """에펠탑은 파리의 철제 격자 구조물로, 1887년부터 1889년까지 건설되었으며,
이후로는 프랑스의 전 세계적으로 인식된 상징이 되었습니다."""},
{"role": "user", "content": """
###document: 애플은 컴퓨터 소프트웨어와 온라인 서비스를 설계, 개발, 판매하는 미국의 다국적 기술 회사로,
캘리포니아 주 쿠퍼티노에 본사를 두고 있습니다.
애플은 아마존, 구글, 마이크로소프트, 페이스북과 함께 빅 테크 기술 회사로 간주됩니다.
"""},
{"role": "assistant", "content": """애플은 소비자 전자 제품과 소프트웨어를 설계하고 판매하는 주요 기술 회사로,
아마존, 구글, 마이크로소프트, 페이스북과 함께 빅 테크로 간주됩니다."""},
{"role": "user", "content": """
###document: 기후 변화는 수십 년에서 수백만 년에 걸친 기간 동안의 기상 패턴의 통계적 분포에서 장기적인 변화를 의미합니다.
이는 평균 기상 조건의 변화, 또는 평균 조건 주변의 기상 분포의 변화를 의미할 수 있습니다.
또한 이것은 기온, 강수량, 또는 바람 패턴의 변화를 포함할 수 있습니다.
"""}
]
for message in messages:
message["content"] = message["content"].replace("\n", "")
b) Tokenize
위와 동일
c) Generate
위와 동일
d) Result
위와 동일
Reference
- [패스트캠퍼스] 8개의 sLM모델로 끝내는 sLM 파인튜닝