HuggingFace镜像/GRM-Gemma2-2B-sftreg
模型介绍文件和版本分析
下载使用量0

开放思维

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。

image/png

上述框架展示了所提出的文本生成正则化方法。该方法显著提高了学习到的奖励模型在各种分布外任务上的准确性,并有效缓解了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.991.684.992.794.6
Ray2333/GRM-gemma2-2B-rewardmodel-ft (我们的模型, 2B)88.493.077.292.291.2
google/gemini-1.5-pro-051488.292.380.687.992.0
RLHFlow/pair-preference-model-LLaMA3-8B87.198.365.889.794.7
Ray2333/GRM-llama3-8B-sftreg(我们的模型, 8B)87.098.667.889.292.3
google/gemini-1.5-pro-092486.894.177.085.890.2
openai/gpt-4o-2024-08-0686.796.176.188.186.6
Ray2333/GRM-llama3.2-3B-sftreg(我们的模型, 3B)85.896.467.188.291.6
Ray2333/GRM-Gemma-2B-rewardmodel-ft (我们的模型, 2B)84.789.475.285.588.8
openai/gpt-4o-2024-05-1384.696.670.486.584.9
sfairXC/FsfairX-LLaMA3-RM-v0.1 (8B)84.499.465.186.886.4
Nexusflow/Starling-RM-34B82.696.957.287.788.5
Ray2333/GRM-Gemma2-2B-sftreg(我们的模型, 2B)81.097.259.686.980.3
Ray2333/GRM-Gemma-2B-sftreg(我们的模型, 2B)75.395.548.780.076.8
berkeley-nest/Starling-RM-7B-alpha (7B)74.69843.488.674.6
Ray2333/Gemma-2B-rewardmodel-baseline(我们的模型, 2B)73.794.146.179.675.0
openbmb/UltraRM-13b (13B)71.396.155.345.882

使用方法

注意 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}
}