Trainer로 모델 파인튜닝하기

PyTorch로 AI 모델 효율적으로 학습시키기

Dennis Lee

Data Engineer, Amazon

데이터 준비

 

분산 학습에서 모델 복제와 데이터 샤딩을 보여주는 다이어그램.

PyTorch로 AI 모델 효율적으로 학습시키기

분산 학습

 

 

데이터 준비, 분산 학습, 효율적 학습, 옵티마이저 등 강좌 주제를 나타내는 순서도.

PyTorch로 AI 모델 효율적으로 학습시키기

Trainer와 Accelerator

Accelerator와 Trainer의 사용 편의성 대 커스터마이즈 가능성을 비교한 차트.

PyTorch로 AI 모델 효율적으로 학습시키기

Trainer와 Accelerator

Accelerator와 Trainer의 사용 편의성 대 커스터마이즈 가능성을 비교한 차트.

PyTorch로 AI 모델 효율적으로 학습시키기

Trainer로 학습 가속화하기

  • Trainer 라이브러리

    from transformers import Trainer
    
  • 각 디바이스에서 모델 병렬 실행

  • 조립 라인처럼 학습 속도 향상
  • 입력 검토: 데이터셋, 모델, 지표
  • 이커머스 감성 분석 개발

병렬 처리 개념을 설명하는 자동차 조립 라인 이미지.

PyTorch로 AI 모델 효율적으로 학습시키기

상품 리뷰 감성 데이터셋

print(dataset)
DatasetDict({
    train: Dataset({
        features: ['Text', 'Label'],
        num_rows: 1000
    }), ...})
print(f'"{dataset["train"]["Text"][0]}": {dataset["train"]["Label"][0]}')
"I love this product!": positive
PyTorch로 AI 모델 효율적으로 학습시키기

레이블을 정수로 변환하기

def map_labels(example):
    if example["Label"] == "negative":
        return {"labels": 0}

else: return {"labels": 1} dataset = dataset.map(map_labels)
print(f'First label: {dataset["train"]["labels"][0]}')
First label: 1
PyTorch로 AI 모델 효율적으로 학습시키기

토크나이저와 모델 정의하기

  • 사전 학습 모델 및 토크나이저 로드:
model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased", 
                                                           num_labels=2)

tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
  • text 필드에 토크나이저 적용:
def encode(examples):

return tokenizer(examples["Text"], padding="max_length", truncation=True, return_tensors="pt")
dataset = dataset.map(encode, batched=True)
print(f'The first tokenized review is {dataset["train"]["input_ids"][0]}.')
The first tokenized review is [101, 1045, 2293, 2023, 4031, 999, 102].
PyTorch로 AI 모델 효율적으로 학습시키기

평가 지표 정의하기

import evaluate


def compute_metrics(eval_predictions):
load_accuracy = evaluate.load("accuracy") load_f1 = evaluate.load("f1")
logits, labels = eval_predictions
predictions = np.argmax(logits, axis=-1)
accuracy = load_accuracy.compute(predictions=predictions, references=labels)[ "accuracy" ]
f1 = load_f1.compute(predictions=predictions, references=labels)["f1"]
return {"accuracy": accuracy, "f1": f1}
PyTorch로 AI 모델 효율적으로 학습시키기

학습 인수

  • output_dir: 모델 저장 위치
  • 하이퍼파라미터 지정 (예: learning_rate, weight_decay)
  • save_strategy: 에포크마다 저장
  • evaluation_strategy: 에포크마다 지표 평가
from transformers import (
    TrainingArguments)

training_args = TrainingArguments(
    output_dir="output_folder",

learning_rate=2e-5, per_device_train_batch_size=16, per_device_eval_batch_size=16, num_train_epochs=2, weight_decay=0.01,
save_strategy="epoch", evaluation_strategy="epoch", )
PyTorch로 AI 모델 효율적으로 학습시키기

Trainer 설정하기

from transformers import Trainer

trainer = Trainer(model=model,

args=training_args,
train_dataset=dataset["train"], eval_dataset=dataset["validation"],
compute_metrics=compute_metrics)
trainer.train()
{'epoch': 1.0, 'eval_loss': 0.79, 'eval_accuracy': 0.00, 'eval_f1': 0.00}
{'epoch': 2.0, 'eval_loss': 0.65, 'eval_accuracy': 0.11, 'eval_f1': 0.15}
print(trainer.args.device)
cpu
PyTorch로 AI 모델 효율적으로 학습시키기

이커머스 감성 분석 실행하기

sample_review = "This product is amazing!"

input_ids = tokenizer.encode(sample_review, return_tensors='pt') print(f"Tokenized review: {input_ids}")
Tokenized review: tensor([[ 101, 2023, 4031, 2003, 6429,  999,  102 ]])
PyTorch로 AI 모델 효율적으로 학습시키기

이커머스 감성 분석 실행하기

output = model(input_ids)
print(f"Output logits: {output.logits}")
Output logits: tensor([[ -0.0538, 0.1300 ]])
predicted_label = torch.argmax(output.logits, dim=1).item()
print(f"Predicted label: {predicted_label}")
Predicted label: 1
sentiment = "Negative" if predicted_label == 0 else "Positive"
print(f'The sentiment of the product review is "{sentiment}."')
The sentiment of the product review is "Positive."
PyTorch로 AI 모델 효율적으로 학습시키기

Trainer의 체크포인트

  • 영화를 일시 정지하듯 최신 체크포인트에서 재개
trainer.train(resume_from_checkpoint=True)
{'epoch': 3.0, 'eval_loss': 0.29, 'eval_accuracy': 0.37, 'eval_f1': 0.51}
{'epoch': 4.0, 'eval_loss': 0.23, 'eval_accuracy': 0.46, 'eval_f1': 0.58}
  • 출력 디렉터리에 저장된 특정 체크포인트에서 재개
trainer.train(resume_from_checkpoint="model/checkpoint-1000")
PyTorch로 AI 모델 효율적으로 학습시키기

연습해 봅시다!

PyTorch로 AI 모델 효율적으로 학습시키기

Preparing Video For Download...