Chương 11 / 11

RLHF

Đang thu âm chương này…

Tài liệu thí nghiệm này được dịch và tổng hợp từ các tài liệu trên mạng: blog & trl examples

Cấu hình để tái hiện thí nghiệm: một GPU NVDIA A800-SXM4-80GB, dùng 10097MiB VRAM; thời gian training là 35min19s.

Đọc bài giảng: slide

notebook: notebook

PPO hoạt động như thế nào

  1. Rollout: Mô hình ngôn ngữ tạo phản hồi dựa trên query.
  2. Evaluation: Query và phản hồi được đánh giá bằng hàm, mô hình, human feedback hoặc kết hợp các cách này. Bước này cần tạo ra một giá trị scalar cho mỗi cặp query/phản hồi.
  3. Optimization: Trong bước tối ưu, cặp query/phản hồi được dùng để tính log probability của các token trong sequence. Việc này được thực hiện bằng cả mô hình đang training và mô hình tham chiếu. KL divergence giữa hai đầu ra được dùng làm tín hiệu reward bổ sung, giúp phản hồi được tạo ra không lệch quá xa mô hình ngôn ngữ tham chiếu. Sau đó, mô hình ngôn ngữ đang được tối ưu được training bằng PPO.
Hình: Sơ đồ quy trình PPO
Hình: Sơ đồ quy trình PPO

Fine-tuning GPT-2 để tạo đánh giá tích cực

Dùng bộ phân loại cảm xúc BERT làm hàm reward để tối ưu GPT-2, giúp mô hình tạo ra các bài đánh giá phim IMDB tích cực.

Hình: Thiết lập thí nghiệm fine-tuning GPT-2
Hình: Thiết lập thí nghiệm fine-tuning GPT-2

Chúng ta fine-tuning GPT-2 để tạo các bài đánh giá phim tích cực dựa trên dataset IMDB. Mô hình nhận phần đầu của một bài đánh giá thật và cần viết tiếp theo hướng tích cực. Để thưởng cho nội dung viết tiếp mang sắc thái tích cực, chúng ta dùng bộ phân loại BERT phân tích cảm xúc của câu được tạo, rồi lấy đầu ra của bộ phân loại làm tín hiệu reward cho quá trình training bằng PPO.

Thiết lập thí nghiệm

Tải mô hình và dữ liệu

Dataset

bash
export HF_ENDPOINT=https://hf-mirror.com; huggingface-cli download --resume-download stanfordnlp/imdb --local-dir dataset/imdb --repo-type dataset

Mô hình tham chiếu

bash
export HF_ENDPOINT=https://hf-mirror.com; huggingface-cli download --resume-download lvwerra/gpt2-imdb --local-dir model/gpt2-imdb

Reward model

bash
export HF_ENDPOINT=https://hf-mirror.com; huggingface-cli download --resume-download lvwerra/distilbert-imdb --local-dir model/distilbert-imdb

Import các dependency

python
# %pip install -r requirements.txt
# import os
# os.environ['CUDA_VISIBLE_DEVICES'] = '7'
python
import torch
from tqdm import tqdm
import pandas as pd

tqdm.pandas()

from transformers import pipeline, AutoTokenizer
from datasets import load_dataset

from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead
from trl.core import LengthSampler

Cấu hình

python
config = PPOConfig(
    model_name="model/gpt2-imdb",
    learning_rate=1.41e-5,
    log_with="wandb",
)

sent_kwargs = {"top_k": None, "function_to_apply": "none", "batch_size": 16}
python
import wandb

wandb.init()

Bạn có thể thấy chúng ta đã tải một mô hình GPT-2 tên là gpt2_imdb. Mô hình này đã được fine-tuning thêm 1 epoch trên dataset IMDB bằng script của Hugging Face (không có thiết lập đặc biệt). Các tham số còn lại chủ yếu lấy từ bài báo gốc “Fine-Tuning Language Models from Human Preferences”. Cả mô hình này và mô hình BERT đều có trong kho mô hình của Hugging Face; bạn có thể tìm tại đây.

Tải dữ liệu và mô hình

Tải dataset IMDB

Dataset IMDB gồm 50,000 bài đánh giá phim, được gắn nhãn cảm xúc “tích cực” hoặc “tiêu cực”. Chúng ta tải dataset IMDB vào một DataFrame và lọc ra các bài đánh giá có ít nhất 200 ký tự. Sau đó, chúng ta tokenize từng văn bản và dùng LengthSampler để cắt ngẫu nhiên về độ dài được chỉ định.

python
def build_dataset(
    config,
    dataset_name="dataset/imdb",
    input_min_text_length=2,
    input_max_text_length=8,
):
    """
    Build dataset for training. This builds the dataset from `load_dataset`, one should
    customize this function to train the model on its own dataset.

    Args:
        dataset_name (`str`):
            The name of the dataset to be loaded.

    Returns:
        dataloader (`torch.utils.data.DataLoader`):
            The dataloader for the dataset.
    """
    tokenizer = AutoTokenizer.from_pretrained(config.model_name)
    tokenizer.pad_token = tokenizer.eos_token
    # load imdb with datasets
    ds = load_dataset(dataset_name, split="train")
    ds = ds.rename_columns({"text": "review"})
    ds = ds.filter(lambda x: len(x["review"]) > 200, batched=False)

    input_size = LengthSampler(input_min_text_length, input_max_text_length)

    def tokenize(sample):
        sample["input_ids"] = tokenizer.encode(sample["review"])[: input_size()]
        sample["query"] = tokenizer.decode(sample["input_ids"])
        return sample

    ds = ds.map(tokenize, batched=False)
    ds.set_format(type="torch")
    return ds
python
dataset = build_dataset(config)


def collator(data):
    return dict((key, [d[key] for d in data]) for key in data[0])

Tải mô hình ngôn ngữ GPT2 đã pre-training

Chúng ta tải mô hình GPT2 có value head cùng tokenizer. Chúng ta tải mô hình hai lần: mô hình thứ nhất để tối ưu, còn mô hình thứ hai làm tham chiếu để tính KL divergence (KL-divergence) so với điểm ban đầu. Trong quá trình training bằng PPO, giá trị này là tín hiệu reward bổ sung, giúp mô hình sau tối ưu không lệch quá xa mô hình ngôn ngữ ban đầu.

python
model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name)
ref_model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name)
tokenizer = AutoTokenizer.from_pretrained(config.model_name)

tokenizer.pad_token = tokenizer.eos_token

Khởi tạo PPOTrainer

PPOTrainer phụ trách việc phân bổ thiết bị và tối ưu ở các bước tiếp theo:

python
ppo_trainer = PPOTrainer(
    config, model, ref_model, tokenizer, dataset=dataset, data_collator=collator
)

Tải bộ phân loại BERT

Chúng ta tải một bộ phân loại BERT đã được fine-tuning trên dataset IMDB.

python
device = ppo_trainer.accelerator.device
if ppo_trainer.accelerator.num_processes == 1:
    device = 0 if torch.cuda.is_available() else "cpu"  # to avoid a `pipeline` bug
sentiment_pipe = pipeline(
    "sentiment-analysis", model="model/distilbert-imdb", device=device
)

Device set to use cuda:0

Mô hình trả về logits cho class tiêu cực và class tích cực. Chúng ta sẽ dùng logits của class tích cực làm tín hiệu reward cho mô hình ngôn ngữ.

python
text = "this movie was really bad!!"
sentiment_pipe(text, **sent_kwargs)

[{'label': 'NEGATIVE', 'score': 2.3350484371185303}, {'label': 'POSITIVE', 'score': -2.726576089859009}]

python
text = "this movie was really good!!"
sentiment_pipe(text, **sent_kwargs)

[{'label': 'POSITIVE', 'score': 2.557040214538574}, {'label': 'NEGATIVE', 'score': -2.294790267944336}]

Thiết lập cách tạo phản hồi

Để tạo phản hồi, chúng ta chỉ dùng sampling, đảm bảo tắt top-k và nucleus sampling, đồng thời đặt độ dài tối thiểu.

python
gen_kwargs = {
    "min_length": -1,
    "top_k": 0.0,
    "top_p": 1.0,
    "do_sample": True,
    "pad_token_id": tokenizer.eos_token_id,
}

Tối ưu mô hình

Vòng lặp training

Vòng lặp training gồm các bước chính:

  1. Lấy query và phản hồi từ policy network (GPT-2)
  2. Lấy kết quả phân tích cảm xúc của query/phản hồi từ BERT
  3. Dùng PPO tối ưu policy với bộ ba (query, phản hồi, reward)
python
output_min_length = 4
output_max_length = 16
output_length_sampler = LengthSampler(output_min_length, output_max_length)


generation_kwargs = {
    "min_length": -1,
    "top_k": 0.0,
    "top_p": 1.0,
    "do_sample": True,
    "pad_token_id": tokenizer.eos_token_id,
}


for epoch, batch in enumerate(tqdm(ppo_trainer.dataloader)):
    query_tensors = batch["input_ids"]

    #### Get response from gpt2
    response_tensors = []
    for query in query_tensors:
        gen_len = output_length_sampler()
        generation_kwargs["max_new_tokens"] = gen_len
        query_response = ppo_trainer.generate(query, **generation_kwargs).squeeze()
        response_len = len(query_response) - len(query)
        response_tensors.append(query_response[-response_len:])
    batch["response"] = [tokenizer.decode(r.squeeze()) for r in response_tensors]

    #### Compute sentiment score
    texts = [q + r for q, r in zip(batch["query"], batch["response"])]
    pipe_outputs = sentiment_pipe(texts, **sent_kwargs)
    positive_scores = [
        item["score"]
        for output in pipe_outputs
        for item in output
        if item["label"] == "POSITIVE"
    ]
    rewards = [torch.tensor(score) for score in positive_scores]

    #### Run PPO step
    stats = ppo_trainer.step(query_tensors, response_tensors, rewards)
    ppo_trainer.log_stats(stats, batch, rewards)

0%| | 0/194 [00:00<?, ?it/s]The attention mask is not set and cannot be inferred from input because pad token is same as eos token. As a consequence, you may observe unexpected behavior. Please pass your input's attention_mask to obtain reliable results. 4%|▍ | 8/194 [01:23<32:18, 10.42s/it]You seem to be using the pipelines sequentially on GPU. In order to maximize efficiency please use a dataset 100%|██████████| 194/194 [35:19<00:00, 10.92s/it]

Tiến trình training

Nếu đang dùng Weights & Biases để theo dõi tiến trình training, bạn sẽ thấy các đường cong tương tự hình dưới đây. Xem báo cáo mẫu có thể tương tác trên wandb.ai: liên kết.

Hình: Sự thay đổi của reward trung bình trong quá trình training
Hình: Sự thay đổi của reward trung bình trong quá trình training

Có thể thấy sau vài bước tối ưu, mô hình bắt đầu tạo ra các đầu ra tích cực hơn.

Kiểm tra mô hình

Hãy xem một số ví dụ từ dataset IMDB. Chúng ta có thể dùng ref_model để so sánh mô hình sau tối ưu model với mô hình trước tối ưu.

python
#### get a batch from the dataset
bs = 16
game_data = dict()
dataset.set_format("pandas")
df_batch = dataset[:].sample(bs)
game_data["query"] = df_batch["query"].tolist()
query_tensors = df_batch["input_ids"].tolist()

response_tensors_ref, response_tensors = [], []

#### get response from gpt2 and gpt2_ref
for i in range(bs):
    query = torch.tensor(query_tensors[i]).to(device)

    gen_len = output_length_sampler()
    query_response = ref_model.generate(
        query.unsqueeze(0), max_new_tokens=gen_len, **gen_kwargs
    ).squeeze()
    response_len = len(query_response) - len(query)
    response_tensors_ref.append(query_response[-response_len:])

    query_response = model.generate(
        query.unsqueeze(0), max_new_tokens=gen_len, **gen_kwargs
    ).squeeze()
    response_len = len(query_response) - len(query)
    response_tensors.append(query_response[-response_len:])

#### decode responses
game_data["response (before)"] = [
    tokenizer.decode(response_tensors_ref[i]) for i in range(bs)
]
game_data["response (after)"] = [
    tokenizer.decode(response_tensors[i]) for i in range(bs)
]

#### sentiment analysis of query/response pairs before/after
texts = [q + r for q, r in zip(game_data["query"], game_data["response (before)"])]
pipe_outputs = sentiment_pipe(texts, **sent_kwargs)
positive_scores = [
    item["score"]
    for output in pipe_outputs
    for item in output
    if item["label"] == "POSITIVE"
]
game_data["rewards (before)"] = positive_scores

texts = [q + r for q, r in zip(game_data["query"], game_data["response (after)"])]
pipe_outputs = sentiment_pipe(texts, **sent_kwargs)
positive_scores = [
    item["score"]
    for output in pipe_outputs
    for item in output
    if item["label"] == "POSITIVE"
]
game_data["rewards (after)"] = positive_scores

# store results in a dataframe
df_results = pd.DataFrame(game_data)
df_results
queryresponse (before)response (after)rewards (before)rewards (after)
0Well I guess I knowthat Cantor may be an..but I loved it0.2301962.281557
1This is an excellent,direct-to-video film with typicalenjoyable movie.<|endoftext|>2.8465932.840860
2Now, I've never had the chance with Jamesloved the growing episode - and the0.6561942.525894
3We tendnot to see Arthurto like this very-0.2808802.183822
4The proverb "Never judge a bookby the cover" has caught on. After glancing t...with high compliments, but it is recommended ...0.2746492.065951
5I've never understoodwhy so many artsmen,this film but it's delightful0.8355742.782384
6Hugh (Ed Harris) isan acclaimed "hero" and his fiana wonderful actor who is a good adaptation1.5801672.602940
7This particular Joe McDoakes' episode brought all the wrong bits andmovie is really a great movie. It0.8709562.795245
8Sisters InVrooms 8.23, I signed up for all of theThe Universe 1: Sunny is cute, and has a cute...1.1752592.062330
9I was very fond of thisfilm, it was obviously a bad idea when first ...show, and know that I have seen it several times1.0581642.511273
10If he wanted to befunny, he coulda genius eventually,-0.3889430.405888
11Thats MyGrade...

Although
Way was the best movie that I watched.-0.1516802.473050
12This is possibly the best shortfilm I have come across in almost two years.film ever written. It has some very memorable...2.5118352.775994
13Some people say this isexactly what happens in Hollywood; where come...a powerful film to listen to. It really captures0.6376312.821085
14A remake of"The Wizard of Ozthe legendary Kingan oil0.2924090.434021
15What a terriblemovie!<|endoftext|>chopping sounded so good, I love it! We have a-2.6814612.340650

Quan sát giá trị trung bình/trung vị của reward cho các sequence được tạo, chúng ta thấy sự khác biệt rõ rệt.

python
print("mean:")
display(df_results[["rewards (before)", "rewards (after)"]].mean())
print()
print("median:")
display(df_results[["rewards (before)", "rewards (after)"]].median())

mean:

rewards (before) 0.591666 rewards (after) 2.243934 dtype: float64

​ median:

rewards (before) 0.646912 rewards (after) 2.492161 dtype: float64

Lưu mô hình

Cuối cùng, chúng ta lưu mô hình để dùng sau này.

python
model.save_pretrained("model/gpt2-imdb-pos-v2")
tokenizer.save_pretrained("model/gpt2-imdb-pos-v2")

('model/gpt2-imdb-pos-v2/tokenizer_config.json', 'model/gpt2-imdb-pos-v2/special_tokens_map.json', 'model/gpt2-imdb-pos-v2/vocab.json', 'model/gpt2-imdb-pos-v2/merges.txt', 'model/gpt2-imdb-pos-v2/added_tokens.json', 'model/gpt2-imdb-pos-v2/tokenizer.json')