data_process_bq / script /reward_acc.py
bingqin111's picture
Upload folder using huggingface_hub
3d27cfe verified
Raw
History Blame Contribute Delete
7.27 kB
#统一方案v2(v1基础上统一截断、填充、eos_token等)
#数据读取改为json格式,适配chat模型
#定义新的格式化函数:利用 chat_template 将列表转为字符串
#添加 config.pad_token_id = tokenizer.pad_token_id
#将 config.std 改为 getattr(config, "std", None),解决配置中缺失 mean/std 字段时的 AttributeError
#将 batch["chosen_prompt"] 替换为 batch["messages"],将 batch["reject"] 替换为 batch["rejected"],适配 JSON 数据格式
#在 sample_table.add_data 中对列表数据(如 messages)添加 str() 转换,防止日志记录出错
import torch, wandb, pandas as pd
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoConfig
import os
# === 参数 ===
rm_path = "/home/LLaMA-Factory/output/mistral-7B_rm_instag_281_1_64_A_6k*3_BCD_m/merged_model"
data_path = "/home/DataProcess/data/test_1w_chatml_closed_numdel_replaced.json"
save_path = "/home/DataProcess/data/test_1w_chatml_closed_numdel_replaced_scored_by_rmv3.json"
batch_size = 16
max_length = 4096
# === wandb ===
wandb.init(project="reward_model_scoring", name="rmv2.2_acc_1")
# === 模型 & tokenizer ===
tokenizer = AutoTokenizer.from_pretrained(rm_path, trust_remote_code=True)
tokenizer.padding_side = "left" # ← 修改
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
tokenizer.pad_token_id = tokenizer.eos_token_id
config = AutoConfig.from_pretrained(rm_path)
config.num_labels = 1 # reward head
config.pad_token_id = tokenizer.pad_token_id
model = AutoModelForSequenceClassification.from_pretrained(
rm_path, config=config, device_map="auto")
model.config.pad_token_id = tokenizer.pad_token_id
model.eval()
device = next(model.parameters()).device
# 读取 json 文件
df = pd.read_json(data_path).reset_index(drop=True)
# 定义新的格式化函数:利用 chat_template 将列表转为字符串
def format_chat_input(history, response_list, tokenizer):
"""
history: list, 对应 json 中的 "messages"
response_list: list, 对应 json 中的 "chosen" 或 "rejected"
"""
# 拼接历史对话和当前的回复
full_conversation = history + response_list
# 使用 tokenizer 的聊天模板转为字符串 (例如转为 <|im_start|>user...<|im_end|>)
# tokenize=False 表示只返回字符串,不返回 ID
try:
txt = tokenizer.apply_chat_template(full_conversation, tokenize=False, add_generation_prompt=False)
except Exception as e:
# 如果模型没有模板(很少见),则手动拼接作为兜底
txt = ""
for msg in full_conversation:
txt += f"{msg['role']}: {msg['content']}\n"
# 依然保留 V2 脚本的核心逻辑:强制检查并添加 EOS
if not txt.endswith(tokenizer.eos_token):
txt += tokenizer.eos_token
return txt
def encode_batch(chosen_texts, rejected_texts, tokenizer, max_length, device):
# 1 tokenize
ch = tokenizer(chosen_texts, add_special_tokens=False,
truncation=True, max_length=max_length, padding=False)
rj = tokenizer(rejected_texts, add_special_tokens=False,
truncation=True, max_length=max_length, padding=False)
ids1, mask1 = ch["input_ids"], ch["attention_mask"]
ids2, mask2 = rj["input_ids"], rj["attention_mask"]
# 2 ensure eos 存在
for arr_ids, arr_mask in ((ids1, mask1), (ids2, mask2)):
for i in range(len(arr_ids)):
arr_ids[i][-1] = tokenizer.eos_token_id
arr_mask[i][-1] = 1
# 3 left-pad 到 joint_max
joint_max = max(max(len(x) for x in ids1), max(len(x) for x in ids2))
lpad = lambda seq, pad: [pad]*(joint_max-len(seq)) + seq
ids1 = [lpad(x, tokenizer.pad_token_id) for x in ids1]
ids2 = [lpad(x, tokenizer.pad_token_id) for x in ids2]
mask1 = [lpad(x, 0) for x in mask1]
mask2 = [lpad(x, 0) for x in mask2]
input_ids = torch.tensor(ids1 + ids2, dtype=torch.long).to(device)
attn_masks = torch.tensor(mask1 + mask2, dtype=torch.long).to(device)
return input_ids, attn_masks, len(chosen_texts)
# === 推理 ===
chosen_scores, rejected_scores, accs = [], [], []
sample_table = wandb.Table(columns=["index","prompt","chosen","rejected",
"chosen_score","rejected_score","delta","acc"])
for i in tqdm(range(0, len(df), batch_size)):
batch = df.iloc[i:i+batch_size]
chosen_texts = []
rejected_texts = []
# 必须遍历每一行,因为 apply_chat_template 不能直接处理 DataFrame 列
for _, row in batch.iterrows():
# row["messages"] 是历史记录
# row["chosen"] 是 [{"role": "assistant", "content": "..."}]
c_txt = format_chat_input(row["messages"], row["chosen"], tokenizer)
r_txt = format_chat_input(row["messages"], row["rejected"], tokenizer)
chosen_texts.append(c_txt)
rejected_texts.append(r_txt)
input_ids, attn_masks, split = encode_batch(chosen_texts, rejected_texts, tokenizer, max_length, device)
with torch.no_grad():
rewards = model(input_ids=input_ids, attention_mask=attn_masks).logits.squeeze(-1)
model_std = getattr(config, "std", None)
model_mean = getattr(config, "mean", None)
if model_std is not None and model_mean is not None:
rewards = rewards * model_std + model_mean
chosen_r, rejected_r = rewards[:split], rewards[split:]
for j in range(len(chosen_r)):
idx = i + j
c, r = chosen_r[j].item(), rejected_r[j].item()
delta = c - r
acc = int(delta > 0)
chosen_scores.append(c)
rejected_scores.append(r)
accs.append(acc)
avg_acc = sum(accs) / len(accs)
print(f"[{idx}] acc={acc}, chosen={c:.3f}, rejected={r:.3f}, Δ={delta:.3f} | avg acc={avg_acc:.3f}")
sample_table.add_data(idx,
str(batch["messages"].iloc[j]), # Prompt (历史对话)
str(batch["chosen"].iloc[j]), # Chosen
str(batch["rejected"].iloc[j]), # Rejected
c, r, delta, acc)
# === 结果 ===
df["chosen_score"] = chosen_scores
df["rejected_score"] = rejected_scores
df["delta"] = df["chosen_score"] - df["rejected_score"]
df["acc"] = accs
accuracy = df["acc"].mean()
mean_chosen = df["chosen_score"].mean()
mean_reject = df["rejected_score"].mean()
mean_delta = df["delta"].mean()
print(f"\nAccuracy = {accuracy:.3f}")
print(f"mean_chosen = {mean_chosen:.3f}, mean_rejected = {mean_reject:.3f}, mean_delta = {mean_delta:.3f}")
# 确保目录存在
os.makedirs(os.path.dirname(save_path), exist_ok=True)
# 保存为 JSON 列表格式 (orient="records"),确保中文不转义 (force_ascii=False)
df.to_json(save_path, orient="records", force_ascii=False, indent=4)
print(f"\n[Success] Scored data saved to: {save_path}")
wandb.log({
"samples_table": sample_table,
"final_accuracy": accuracy,
"mean_chosen_score": mean_chosen,
"mean_rejected_score": mean_reject,
"mean_delta_score": mean_delta,
})
wandb.finish()