探索預訓練 LLM

Reinforcement Learning from Human Feedback(RLHF)

Mina Parham

AI Engineer

微調為何重要

說明 RLHF 流程的示意圖。

Reinforcement Learning from Human Feedback(RLHF)

微調為何重要

顯示具有輸入與輸出的 LLM 示意圖。

Reinforcement Learning from Human Feedback(RLHF)

LLM 微調分步指南

代表訓練辨識推文情緒的 LLM 圖示。

Reinforcement Learning from Human Feedback(RLHF)

LLM 微調分步指南

代表訓練辨識推文情緒但輸出錯誤的 LLM 圖示。

Reinforcement Learning from Human Feedback(RLHF)

LLM 微調分步指南

代表以大型資料集預訓練、用於辨識推文情緒的 LLM 圖示。

Reinforcement Learning from Human Feedback(RLHF)

步驟 1:載入要用的資料

from datasets import load_dataset
import pandas as pd

# `load_dataset` simplifies loading and preprocessing datasets from various sources
# It provides easy access to a wide range of datasets with minimal setup
dataset = load_dataset("mteb/tweet_sentiment_extraction")
df = pd.DataFrame(dataset['train'])
    id               text                                        label   label_text
0   cb774db0d1       I'd have responded, if I were going         1       neutral
1   549e992a42       Sooo SAD I will miss you in San Diego!!!    0       negative
2   08ac60f138       my boss is bullying me...                   0       negative
Reinforcement Learning from Human Feedback(RLHF)

步驟 2:選擇預訓練模型

from transformers import AutoModelForCausalLM

# AutoModelForCausalLM simplifies loading and switching models
model = AutoModelForCausalLM.from_pretrained("openai-gpt")

 

  • 因果模型:前一個 token 會「導致」後續的 token
Reinforcement Learning from Human Feedback(RLHF)

步驟 3:分詞器(tokenizer)

from transformers import AutoTokenizer

# `AutoTokenizer` loads the correct tokenizer for the specified model
tokenizer = AutoTokenizer.from_pretrained("openai-gpt")
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
model.resize_token_embeddings(len(tokenizer))

 

  • Padding:讓每批文字長度一致
Reinforcement Learning from Human Feedback(RLHF)

步驟 3:分詞器(tokenizer)

def tokenize_function(examples):
    tokenized = tokenizer(examples["content"], padding="max_length", truncation=True) 
    return tokenized

tokenized_datasets = dataset.map(tokenize_function, batched=True)

 

  • batched 參數:加速處理
Reinforcement Learning from Human Feedback(RLHF)

步驟 4:用 Trainer 方法微調

training_args = TrainingArguments(
   output_dir="test_trainer",
   per_device_train_batch_size=1,
   per_device_eval_batch_size=1,  
   gradient_accumulation_steps=4)
trainer = Trainer(
   model=model,
   args=training_args,
   train_dataset=tokenized_dataset["train"],
   eval_dataset=tokenized_dataset["test"])
trainer.train()
Reinforcement Learning from Human Feedback(RLHF)

一起來練習吧!

Reinforcement Learning from Human Feedback(RLHF)

Preparing Video For Download...