使用 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 模型

定義 tokenizer 與模型

  • 載入預訓練模型與 tokenizer:
model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased", 
                                                           num_labels=2)

tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
  • text 欄位套用 tokenizer:
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 模型

訓練參數(Training arguments)

  • output_dir:儲存模型的位置
  • 指定超參數(例如 learning_rateweight_decay
  • save_strategy:每個 epoch 後儲存
  • evaluation_strategy:每個 epoch 後評估指標
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...