1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
| import pandas as pd import torch from datasets import load_dataset from tqdm import tqdm from transformers import AutoTokenizer, set_seed, pipeline from trl import AutoModelForCausalLMWithValueHead, create_reference_model, PPOConfig, PPOTrainer from trl.core import LengthSampler
model_name = "Wenzhong-GPT2-110M" config = PPOConfig( model_name=model_name, learning_rate=1.41e-5, log_with="tensorboard", batch_size=64, gradient_accumulation_steps=8, mini_batch_size=8, ) sent_kwargs = {"return_all_scores": True, "function_to_apply": "none", "batch_size": 16}
gpt2_tokenizer = AutoTokenizer.from_pretrained(config.model_name) gpt2_tokenizer.pad_token = gpt2_tokenizer.eos_token
set_seed(1)
def build_dataset(input_min_text_length=2, input_max_text_length=8): ds = load_dataset( 'csv', data_files={ "train": "train.tsv", "dev": "dev.tsv", }, delimiter='\t' )['train'] ds = ds.rename_columns({"text_a": "review"}) ds = ds.filter(lambda x: len(x['review']) > 10, batched=False)
input_size = LengthSampler(input_min_text_length, input_max_text_length)
def tokenize(sample): sample["input_ids"] = gpt2_tokenizer.encode(sample["review"][: input_size()]) sample["query"] = gpt2_tokenizer.decode(sample["input_ids"]) return sample
ds = ds.map(tokenize, batched=False) ds.set_format(type="torch") return ds
dataset = build_dataset()
def collator(data): return dict((key, [d[key] for d in data]) for key in data[0])
sentiment_pipe = pipeline( "sentiment-analysis", model='/score_model/checkpoint-1000', device='cuda:1' )
text = "今天天气很好" print(sentiment_pipe(text, **sent_kwargs))
text = '这个电影主角演的真心一般般' print(sentiment_pipe(text, **sent_kwargs))
output_min_length = 16 output_max_length = 32 output_length_sampler = LengthSampler(output_min_length, output_max_length)
model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name) ref_model = create_reference_model(model)
ppo_trainer = PPOTrainer(config, model, ref_model, gpt2_tokenizer, dataset, data_collator=collator)
generation_kwargs = { "min_length": -1,
"top_k": 0, "top_p": 1, "do_sample": True, "pad_token_id": gpt2_tokenizer.eos_token_id, "bos_token_id": gpt2_tokenizer.bos_token_id, "eos_token_id": gpt2_tokenizer.eos_token_id, } device = 'cuda:0'
for i in range(3): for epoch, batch in tqdm(enumerate(ppo_trainer.dataloader)): query_tensors = batch['input_ids'] response_tensors = [] for query in query_tensors: gen_len = output_length_sampler()
response = ppo_trainer.generate(query, **{**generation_kwargs, "max_new_tokens": gen_len}) response_tensors.append(response.squeeze()[-gen_len:]) batch["response"] = [gpt2_tokenizer.decode(r.squeeze()) for r in response_tensors] texts = [q + r for q, r in zip(batch["query"], batch["response"])] pipe_outputs = sentiment_pipe(texts, **sent_kwargs) rewards = [torch.tensor(output[1]["score"]) for output in pipe_outputs]
stats = ppo_trainer.step(query_tensors, response_tensors, rewards) ppo_trainer.log_stats(stats, batch, rewards)
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 = [], []
for i in range(bs): gen_len = output_length_sampler() output = ref_model.generate( torch.tensor(query_tensors[i]).unsqueeze(dim=0).to(device), max_new_tokens=gen_len, **generation_kwargs ).squeeze()[-gen_len:] response_tensors_ref.append(output) output = model.generate( torch.tensor(query_tensors[i]).unsqueeze(dim=0).to(device), max_new_tokens=gen_len, **generation_kwargs ).squeeze()[-gen_len:] response_tensors.append(output)
game_data["response (before)"] = [gpt2_tokenizer.decode(response_tensors_ref[i]) for i in range(bs)] game_data["response (after)"] = [gpt2_tokenizer.decode(response_tensors[i]) for i in range(bs)]
texts = [q + r for q, r in zip(game_data["query"], game_data["response (before)"])] game_data["rewards (before)"] = [output[1]["score"] for output in sentiment_pipe(texts, **sent_kwargs)]
texts = [q + r for q, r in zip(game_data["query"], game_data["response (after)"])] game_data["rewards (after)"] = [output[1]["score"] for output in sentiment_pipe(texts, **sent_kwargs)]
df_results = pd.DataFrame(game_data) print(df_results)
print("mean:") print(df_results[["rewards (before)", "rewards (after)"]].mean()) print() print("median:") print(df_results[["rewards (before)", "rewards (after)"]].median())
model.save_pretrained("gpt2-imdb-pos-v2", push_to_hub=False) gpt2_tokenizer.save_pretrained("gpt2-imdb-pos-v2", push_to_hub=False)
|