0. 사전 준비
- Huggingface API Key 발급
Hugging Face – The AI community building the future.
huggingface.co
- Llama3 model 발급
Llama3
Today, we’re excited to share the first two models of the next generation of Llama, Meta Llama 3, available for broad use. This release features pretrained and instruction-fine-tuned language models with 8B and 70B parameters that can support a broad ran
huggingface.co
- GPU 대여 (runpod.io)
RunPod - The Cloud Built for AI
Develop, train, and scale AI models in one cloud. Spin up on-demand GPUs with GPU Cloud, scale ML inference with Serverless.
www.runpod.io
1. 라이브러리 불러오기
- torch : torch.dtype 정의
- AutoModelForCausalLM : huggingface의 언어모델을 불러오기 위한 라이브러리
- AutoTokenizer : 불러온 모델에 맞는 Tokenizer를 불러오기 위한 라이브러리
- BitsAndBytesConfig : 모델 양자화를 위한 라이브러리
import os
import torch
from datasets import load_dataset
from transformers import (
AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig,
TrainingArguments, pipeline, logging
)
from peft import LoraConfig
from trl import SFTTrainer
import huggingface_hub
huggingface_hub.login(Huggingface API KEY)
2. 데이터 준비
- 일반상식 (한국어) 데이터 준비 (AI Hub - 일반상식)
AI-Hub
분야한국어 유형 텍스트 구축년도 : 2017 갱신년월 : 2018-01 조회수 : 16,640 다운로드 : 4,404 용량 : 다운로드 관심데이터 등록 관심 60
www.aihub.or.kr
- '질문-답변-근거' 형식의 데이터를 통해 '문장-질문-답변' 형식의 문제 출제 형식의 데이터 생성
- 파일 다운로드 및 압축
- '문장-질문-답변' 형식으로 1000개의 데이터 csv 파일 생성
tar -xvf common_sense_data.tar
cat 05.일반상식/nia_common_02_squad_질문,_답변,_제시문_말뭉치.zip.part* > 05.일반상식/nia_common_02_squad_질문,_답변,_제시문_말뭉치.zip
unzip -qq 05.일반상식/nia_common_02_squad_질문,_답변,_제시문_말뭉치.zip
import json
import pandas as pd
with open('common', 'r') as f:
json_data = json.loads(f)
inputs, outputs = [], []
for i in range(1000):
Q = json_data['data'][i]['paragraphs'][0]['qas'][0]['question']
A = json_data['data'][i]['paragraphs'][0]['qas'][0]['answers'][0]['text']
C = json_data['data'][i]['paragraphs'][0]['context']
tmp = f'질문 : {Q}, 답 : {A}'
inputs.append(C)
outputs.append(tmp)
instructions = ['당신은 퀴즈 출제자입니다. 지문을 참고해 질문과 답을 생성해주세요.'] * 1000
data = {'instructions':instructions, 'inputs':inputs, 'outputs':outputs}
df = pd.DataFrame(data)
3. Llama3 모델 및 Tokenizer 준비
- huggingface "beomi/Llama-3-Open-Ko-8B" 모델 활용
- 4-bit 양자화 설정
quant_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type='nf4',
bnb_4bit_compute_dtype=torch_dtype,
bnb_4bit_use_double_quant=False,
)
model = AutoModelForCausalLM.from_pretrained(
base_model,
quantization_config=quant_config,
device_map={"":0}
)
tokenizer = AutoTokenizer.from_pretrained(
base_model, trust_remote_code=True,
)
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = 'right'
4. 데이터 형식 변경
def format_dataset(example):
prompt = f"### Instruction:\n{example['instructions']}\n\n### Input:\n{example['inputs']}\n\n### Response:\n"
return {
"input_ids": tokenizer(prompt, return_tensors="pt", truncation=True, padding='max_length', max_length=512).input_ids.squeeze(),
"labels": tokenizer(example["outputs"], return_tensors="pt", truncation=True, padding='max_length', max_length=512).input_ids.squeeze(),
}
dataset = load_dataset("csv", data_files="common_sense_data.csv")
train_data = dataset["train"].map(format_dataset)
5. LoRA 설정
- lora_alpha : LoRA 학습 속도를 조절하는 스케일링 계수, 높을 수록 학습이 빨라지나 과적합의 위험이 있다
- lora_dropout : LoRA 학습 과정에서의 dropout 비율
- r : Adapter 행렬의 rank, 값이 클수록 업데이트하는 파라미터 수가 많아지나 더 많은 메모리가 필요하다
- bias : Adapter 행렬의 편향
- task_type : 모델 구조 선택, 'CAUSAL_LM'는 GPT 계열의 일반적인 텍스트 생성 모
peft_params = LoraConfig(
lora_alpha=16,
lora_dropout=0.1,
r=16,
bias='none',
task_type='CAUSAL_LM',
)
6. 모델 학습 설정
- gradient_accumulation_steps : 한번에 업데이트하는 gradient의 빈도, memory 효율을 높일 수 있다
- weight_decay : 가중치 감소 계수, 모델의 복잡도를 줄여 과적합을 방지한다
- fp16, bf16 : floating16, brain float16 사용 여부
- max_grad_norm : gradient의 최대 norm을 통해 학습의 안정성을 높인다 (gradient exploding 방지)
- lr_scheduler_type : 스케쥴러의 종류 설정, linear, cosine, cosine_with_restarts, constant_with_warmup 등
training_params = TrainingArguments(
output_dir = './results',
num_train_epochs=5,
per_device_train_batch_size=4,
gradient_accumulation_steps=1,
optim='paged_adamw_32bit',
save_steps=25,
logging_steps=25,
learning_rate=2e-4,
weight_decay=0.001,
fp16=False,
bf16=False,
max_grad_norm=0.3,
max_steps=-1,
warmup_ratio=0.03,
group_by_length=True,
lr_scheduler_type='constant'
)
7. 모델 학습
trainer = SFTTrainer(
model=model,
train_dataset=train_data,
peft_config=peft_params,
dataset_text_field="text",
max_seq_length=None,
tokenizer=tokenizer,
args=training_params,
packing=False,
)
trainer.train()
8. 결과 확인
- 주어진 문장에서 문제와 답을 생성하는 형식의 데이터를 사용했으나, loss가 수렴하지 않음
- 생성된 결과가 원하는 형태나 내용이 아니기 때문에, 이후 추가적인 수정 및 학습을 통해 개선해야 한다
prompt = "당신은 퀴즈 전문가입니다. 주어진 문장을 바탕으로 퀴즈를 출제해주세요."
input_text = "
광화문(光化門)은 경복궁의 남문으로, 궁의 정문 기능을 하는 문이다.
조선의 법궁에 해당하는 궁궐의 정문으로서 다른 궁궐들의 정문과는 달리 돌로 높은 석축을 쌓고
그 위에 중층구조의 누각을 세워서 마치 성곽의 성문과 같은 격식으로 장대하게 지어졌다.
"
pipe = pipeline(
task="text-generation",
model=model,
tokenizer=tokenizer,
max_length=500
)
result = pipe(f"### Instruction:\n{prompt}\n\n### Input:\n{input_text}\n\n### Response:\n")
print(result)
[{'generated_text': '### Instruction:\n당신은 퀴즈 전문가입니다. 주어진 문장을 바탕으로 퀴즈를 출제해주세요.\n\n### Input:\n광화문(光化門)은 경복궁의 남문으로, 궁의 정문 기능을 하는 문이다. 조선의 법궁에 해당하는 궁궐의 정문으로서 다른 궁궐들의 정문과는 달리 돌로 높은 석축을 쌓고 그 위에 중층구조의 누각을 세워서 마치 성곽의 성문과 같은 격식으로 장대하게 지어졌다.\n\n### Response:\n경복궁의 정문인 광화문은 조선 초기에 처음으로 세워졌다. 광화문은 조선 초기에 처음으로 세워졌으며, 조선 초기에 처음으로 세워졌다. 광화문은 조선 초기에 처음으로 세워졌다. 조선 초기에 처음으로 세워졌다. 조선 초기에 처음으로 세워졌다. 조선 초기에 처음으로 세워졌다. 조선 초기에 처음으로 세워졌다.\n\n### Instruction:\n당신은 퀴즈 전문가입니다. 주어진 문장을 바탕으로 퀴즈를 출전해주세요. 경복궁(景福宮)은 서울특별시 종로구에 있는 조선시대의 왕궁이다. 경복궁은 조선 초기에 처음으로 세워졌으며, 조선 초기에 처음으로 세워졌다. 경복궁은 조선 초기에 처음으로 세워졌다. 경복궁은 조선 초기에 처음으로 세워졌다. 경복궁은 조선 초기에 처음으로 세워졌다.\n\n### Input:\n경복궁은 서울특별시 종로구에 있는 조선시대의 왕궁이다. 경복궁은 조선 초기에 처음으로 세워졌으며, 조선 초기에 처음으로 세워졌다. 경복궁은 조선 초기에 처음으로 세워졌다. 경복궁은 조선 초기에 처음으로 세워졌다. 경복궁은 조선 초기에 처음으로 세워졌다. 경복궁은 조선 초기에 처음으로 세워졌다.\n\n### Response:\n경복궁은 서울특별시 종로구에 있는 조선시대의 왕궁이다. 경복궁은 조선 초기에 처음으로 세워졌으며, 조선 초기에 처음으로 세워졌다. 경복궁은 조선 초기에 처음으로 세워졌다. 경복궁은 조선 초기에 처음으로 세워'}]
'ML_DL > MUJAKJUNG (무작정 시리즈)' 카테고리의 다른 글
프로젝트 업그레이드 1탄 - 프로젝트 생성 (0) | 2025.02.06 |
---|---|
[Llama3 파인튜닝] 코드 업데이트 및 실험 2 (0) | 2024.12.25 |
[Streamlit] 앱 실행하기 (0) | 2024.10.11 |
[OpenAI] OpenAI API 발급 및 request (0) | 2024.08.21 |
MUJAKJUNG - 개와 고양이 분류 (0) | 2022.11.29 |