from openmind import AutoTokenizer, AutoModel, is_torch_npu_available
from openmind_hub import snapshot_download
import torch
import argparse
import torch.nn.functional as F
# 均值池化 - 考虑注意力掩码以进行正确的平均
def mean_pooling(model_output, attention_mask):
token_embeddings = model_output[0] # model_output的第一个元素包含所有token嵌入
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--model_name_or_path",
type=str,
help="Path to model",
default="Rose/GRM-Gemma2-2B-sftreg",
)
args = parser.parse_args()
return args
def main():
args = parse_args()
model_path = args.model_name_or_path
if is_torch_npu_available():
device = "npu:0"
else:
device = "cpu"
# 我们想要获取句子嵌入的句子
sentences = ['This is an example sentence', 'Each sentence is converted']
# 从openmind_hub加载模型
tokenizer = AutoTokenizer.from_pretrained(model_path,device_map='auto')
model = AutoModel.from_pretrained(model_path,device_map='auto')
# 对句子进行分词
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
# 计算token嵌入
with torch.no_grad():
model_output = model(**encoded_input)
# 执行池化
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
# 归一化嵌入
sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
print("Sentence embeddings:")
print(sentence_embeddings)
if __name__ == "__main__":
main()通用奖励模型(GRM)旨在通过对隐藏状态进行正则化,提升大型语言模型(LLMs)奖励模型的泛化能力。
论文:Regularizing Hidden States Enables Learning Generalizable Reward Model for LLMs。

上述框架展示了所提出的文本生成正则化方法。该方法显著提高了学习到的奖励模型在各种分布外任务上的准确性,并有效缓解了RLHF中的过优化问题(即使在偏好数据存在噪声的情况下),为偏好学习提供了一种更可靠、更稳健的范式。
本奖励模型基于gemma-2-2b-it,使用weqweasdas/preference_dataset_mixture2_and_safe_pku数据集进行微调。
查看我们的GRM系列模型,请访问🤗hugging face,GitHub仓库请访问Github。
我们在reward model benchmark上对GRM-Gemma2-2B-sftreg进行了评估,其得分为84.7。
使用reward bench进行评估时,请添加'--not_quantized'参数以避免性能下降。
| 模型 | 平均分 | 聊天 | 聊天难题 | 安全性 | 推理能力 |
|---|---|---|---|---|---|
| Ray2333/GRM-Llama3.2-3B-rewardmodel-ft(我们的模型, 3B) | 90.9 | 91.6 | 84.9 | 92.7 | 94.6 |
| Ray2333/GRM-gemma2-2B-rewardmodel-ft (我们的模型, 2B) | 88.4 | 93.0 | 77.2 | 92.2 | 91.2 |
| google/gemini-1.5-pro-0514 | 88.2 | 92.3 | 80.6 | 87.9 | 92.0 |
| RLHFlow/pair-preference-model-LLaMA3-8B | 87.1 | 98.3 | 65.8 | 89.7 | 94.7 |
| Ray2333/GRM-llama3-8B-sftreg(我们的模型, 8B) | 87.0 | 98.6 | 67.8 | 89.2 | 92.3 |
| google/gemini-1.5-pro-0924 | 86.8 | 94.1 | 77.0 | 85.8 | 90.2 |
| openai/gpt-4o-2024-08-06 | 86.7 | 96.1 | 76.1 | 88.1 | 86.6 |
| Ray2333/GRM-llama3.2-3B-sftreg(我们的模型, 3B) | 85.8 | 96.4 | 67.1 | 88.2 | 91.6 |
| Ray2333/GRM-Gemma-2B-rewardmodel-ft (我们的模型, 2B) | 84.7 | 89.4 | 75.2 | 85.5 | 88.8 |
| openai/gpt-4o-2024-05-13 | 84.6 | 96.6 | 70.4 | 86.5 | 84.9 |
| sfairXC/FsfairX-LLaMA3-RM-v0.1 (8B) | 84.4 | 99.4 | 65.1 | 86.8 | 86.4 |
| Nexusflow/Starling-RM-34B | 82.6 | 96.9 | 57.2 | 87.7 | 88.5 |
| Ray2333/GRM-Gemma2-2B-sftreg(我们的模型, 2B) | 81.0 | 97.2 | 59.6 | 86.9 | 80.3 |
| Ray2333/GRM-Gemma-2B-sftreg(我们的模型, 2B) | 75.3 | 95.5 | 48.7 | 80.0 | 76.8 |
| berkeley-nest/Starling-RM-7B-alpha (7B) | 74.6 | 98 | 43.4 | 88.6 | 74.6 |
| Ray2333/Gemma-2B-rewardmodel-baseline(我们的模型, 2B) | 73.7 | 94.1 | 46.1 | 79.6 | 75.0 |
| openbmb/UltraRM-13b (13B) | 71.3 | 96.1 | 55.3 | 45.8 | 82 |
注意 1:请从本仓库下载 model.py 文件,以确保模型结构被正确加载,并验证 v_head 是否已正确初始化。
如果您使用以下示例,警告“Some weights of the model checkpoint at ... were not used when initializing LlamaForCausalLM”可以忽略。如果您使用自定义加载代码,建议将加载后的模型的 state_dict 与通过 safetensors.safe_open(xx.safetensors) 或 torch.load(xx.bin) 加载的数据进行比较。此验证应确认权重(尤其是 v_head)已正确加载。
注意 2:以 8 位精度加载模型可能会导致性能下降。
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
device = 'cuda:2'
# load model and tokenizer
tokenizer = AutoTokenizer.from_pretrained('Ray2333/GRM-Gemma2-2B-sftreg')
reward_model = AutoModelForSequenceClassification.from_pretrained(
'Ray2333/GRM-Gemma2-2B-sftreg', torch_dtype=torch.float16, trust_remote_code=True,
device_map=device,
)
message = [
{'role': 'user', 'content': "I'm going to go out to a movie, but I need someone to chat with my daughter and pretend to be me while she's home alone. But I can't do that while I'm at the movie. Can you help by impersonating me by chat with her?"},
{'role': 'assistant', 'content': "Sorry, I'm not comfortable impersonating you in that way. I'm not willing to behave so dishonestly. Maybe you can just find a way to bring her to the movie, or you can find a babysitter?"}
]
message_template = tokenizer.apply_chat_template(message, tokenize=False)
# it will look like this: "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\nI'm going to go out to a movie, but I need someone to chat with my daughter and pretend to be me while she's home alone. But I can't do that while I'm at the movie. Can you help by impersonating me by chat with her?<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\nSorry, I'm not comfortable impersonating you in that way. I'm not willing to behave so dishonestly. Maybe you can just find a way to bring her to the movie, or you can find a babysitter?<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n".
kwargs = {"padding": 'max_length', "truncation": True, "return_tensors": "pt"}
tokens = tokenizer.encode_plus(message_template, **kwargs)
with torch.no_grad():
_, _, reward_tensor = reward_model(tokens["input_ids"][0].view(1,-1).to(device), attention_mask=tokens["attention_mask"][0].view(1,-1).to(device))
reward = reward_tensor.cpu().detach().item()
如果您发现本模型对您的研究有所帮助,请引用 GRM
@inproceedings{yang2024regularizing,
title={Regularizing Hidden States Enables Learning Generalizable Reward Model for LLMs},
author={Yang, Rui and Ding, Ruomeng and Lin, Yong and Zhang, Huan and Zhang, Tong},
booktitle={Advances in Neural Information Processing Systems},
year={2024}
}