/ Модель

Характеристики

Лицензия
MIT
Архитектура
deberta · dense
Опубликована
6 ноя 2023

PairRM

Генерация текстаТекст → текст3 профессии

PairRM сравнивает варианты ответов на инструкцию и ранжирует их для выбора предпочтительного ответа, оценки LLM или RLHF.

959скачиваний за 30 дней209лайковвеса обновлены22 янв 2024

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

PairRM — попарная модель оценки ответов больших языковых моделей, разработанная проектом LLM-Blender. Она принимает инструкцию и два варианта ответа, затем сравнивает их и оценивает относительное качество. Модель предназначена для ранжирования ответов, выбора лучшего из нескольких сгенерированных вариантов и использования в оценке или выравнивании моделей с помощью RLHF.

PairRM основана на архитектуре DeBERTa-v3-large и содержит около 0,4 млрд параметров. Благодаря двунаправленному вниманию она сравнивает ответы напрямую, а не оценивает каждый независимо. Общая длина входа ограничена 2048 токенами: до 1224 токенов для инструкции и 412 токенов для каждого кандидата.

Модель обучена на наборах данных с человеческими предпочтениями, включая WebGPT Comparisons, Anthropic HH-RLHF, Chatbot Arena Conversations и UltraFeedback. Карточка сообщает о высокой согласованности оценок с человеческими предпочтениями, но фактическое качество зависит от задачи и набора кандидатов. Модель ориентирована на английский язык. Распространяется по лицензии MIT.

Сценарии применения

  • ранжирование ответов LLM по пользовательской инструкции
  • выбор лучшего ответа из нескольких сгенерированных вариантов
  • попарная оценка качества ответов чат-ботов
  • оценка моделей на соответствие человеческим предпочтениям
  • подготовка оценок для выравнивания LLM методом RLHF

Ограничения

Модель рассчитана прежде всего на английский язык и оценивает относительное качество только для переданных кандидатов; её оценки не гарантируют совпадения с человеческими предпочтениями для каждой задачи. Общая длина входа ограничена 2048 токенами.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

Pairwise Reward Model for LLMs (PairRM) from LLM-Blender

News

Introduction

Pairwise Reward Model (PairRM) takes an instruction and a pair of output candidates as the input, and output a score for each candidate to measure their relative quality. PairRM can be used to (re-)rank a list of candidate outputs and thus can be used an LLM evaluator to efficiently assess the quality of LLMs in local environment. PairRM can also be used to enhance the decoding by best-of-n sampling (i.e., reranking N sampled outputs). Apart from that, one can also use PairRM to further align instruction-tuned LLMs with RLHF methods.

Unlike the other RMs that encode and score each candidate respectively, PairRM takes a pair of candidates and compares them side-by-side to indentify the subtle differences between them. Also, PairRM is based on microsoft/deberta-v3-large, and thus it is super efficient: 0.4B. We trained PairRM on a diverse collection of six human-preference datasets (see more here).

PairRM is part of the LLM-Blender project (ACL 2023). Please see our paper above to know more.

Installation

  • First install llm-blender
pip install git+https://github.com/yuchenlin/LLM-Blender.git
  • Then load PairRM:
import llm_blender
blender = llm_blender.Blender()
blender.loadranker("llm-blender/PairRM") # load PairRM

Usage

Use Case 1: Comparing/Ranking output candidates given an instruction

  • Ranking a list candidate responses
inputs = ["hello, how are you!", "I love you!"]
candidates_texts = [["get out!", "hi! I am fine, thanks!", "bye!"], 
                    ["I love you too!", "I hate you!", "Thanks! You're a good guy!"]]
ranks = blender.rank(inputs, candidates_texts, return_scores=False, batch_size=1)
# ranks is a list of ranks
# ranks[i][j] represents the ranks of candidate-j for input-i
"""
ranks -->
array([[3, 1, 2], # it means "hi! I am fine, thanks!" ranks the 1st, "bye" ranks the 2nd, and "get out!" ranks the 3rd. 
       [1, 3, 2]], # it means "I love you too"! ranks the the 1st, and "I hate you!" ranks the 3rd.
       dtype=int32) 

"""
  • Directly comparing two candidate responses
inputs = ["hello!", "I love you!"]
candidates_A = ["hi!", "I hate you!"]
candidates_B = ["f**k off!", "I love you, too!"]
comparison_results = blender.compare(inputs, candidates_A, candidates_B)
# comparison_results is a list of bool, where comparison_results[i] denotes
       # whether candidates_A[i] is better than candidates_B[i] for inputs[i]
# Example: comparison_results[0]--> True 
conv1 = [
    {
        "content": "hello",
        "role": "USER"
    },
    {
        "content": "[assistant1‘s response 1]",
        "role": "ASSISTANT"
    },
    ...
]
conv2 = [
    {
        "content": "hello",
        "role": "USER"
    },
    {
        "content": "[assistant2's response 1]",
        "role": "ASSISTANT"
    },
    ...
]
comparison_results = blender.compare_conversations([conv1], [conv2])
# comparison_results is a list of bool, where each element denotes whether all the responses in conv1 together is better than that of conv2

Use Case 2: Best-of-n Sampling (Decoding Enhancment)

Best-of-n Sampling, aka, rejection sampling, is a strategy to enhance the response quality by selecting the one that was ranked highest by the reward model (see more in OpenAI WebGPT section 3.2 and OpenAI Blog). Best-of-n sampling with PairRM is a very easy way to imporve your LLMs with only a few changes of your inference code:

# loading models 
import llm_blender
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta")
model = AutoModelForCausalLM.from_pretrained("HuggingFaceH4/zephyr-7b-beta", device_map="auto")
system_message = {"role": "system", "content": "You are a friendly chatbot."}

# formatting your inputs 
inputs = ["can you tell me a joke about OpenAI?"]
messages = [[system_message, {"role": "user", "content": _input}] for _input in inputs]
prompts = [tokenizer.apply_chat_template(m, tokenize=False, add_generation_prompt=True) for m in messages]

# Conventional generation method 
input_ids = tokenizer(prompts[0], return_tensors="pt").input_ids
sampled_outputs = model.generate(input_ids, do_sample=True, top_k=50, top_p=0.95, num_return_sequences=1)
print(tokenizer.decode(sampled_outputs[0][len(input_ids[0]):], skip_special_tokens=False))
# --> The output could be a bad case such as a very short one, e.g., `Sure` 

# PairRM for best-of-n sampling 
blender = llm_blender.Blender()
blender.loadranker("llm-blender/PairRM") # load ranker checkpoint
outputs = blender.best_of_n_generate(model, tokenizer, prompts, n=10)

print("### Prompt:\n", prompts[0])
print("### best-of-n generations:\n", outputs[0])
# --> The output will be much more stable and consistently better than single sampling, for example: 
""" 
Sure, here's a joke about OpenAI:

Why did OpenAI decide to hire a mime as their new AI researcher?

Because they wanted someone who could communicate complex ideas without making a sound!

(Note: This is a joke, not a reflection of OpenAI's actual hiring practices.)
"""

Use case 3: RLHF

PairRM has been trained on various high-quality and large-scale datasets with human preference annotations and shown great correlation with human preferences with an extremely small model size (0.4B), approching the performance of GPT-4. PairRM will better help the future alignment of LLMs in a more efficient and effective way. With a blender.compare() function, you can apply PairRM to popular RLHF toolkits such as trl.

🔥 Check more details on our example jupyter notebook usage: blender_usage.ipynb

Learn more in our LLM-Blender Github README.md

Statistics

Context length

PairRanker typeSource max lengthCandidate max lengthTotal max length
pair-ranker (our previous version)128128384
PairRM (This model)12244122048

Training Datasets

Performance

PairRM has been trained on various high-quality and large-scale dataset with human preference annotations and exhibits great correlation with human preferences with an extremly small model size (0.4B), approching the performance of GPT-4.

We test the pairwise comparison on

All following results are reported as pairwise comparison accuracies (agreements).

Auto-J Pairwise test data performance

ModelSummExamCodeRewritingCrea WFunc WCommNLPOverall
Closed -source Models
ChatGPT33.340.336.631.648.240.447.645.842.7
Claude -230.636.141.734.248.142.540.648.542.4
GPT -459.751.469.258.366.760.458.365.261.9
Open -source Models
SteamSHP33.329.226.733.340.731.351.451.940.6
PandaLM29.233.331.723.343.532.944.848.938.9
LLaMA -2-Chat -13B20.827.819.22031.527.535.831.829
Vicuna -13B-v1.530.623.63528.336.137.545.539.837.3
WizardLM -13B-v1.222.220.832.519.228.725.429.23327.8
LLAMA -2-chat -70B34.733.336.735.851.454.247.247.745.9
AUTO -J (13b)45.838.959.247.554.657.15857.654.8
UltraRM (13b)56.9443.0655.053.3367.1364.1756.2559.8559.85
PairRM (0.4b)56.9452.7858.3355.8361.5759.1757.6462.559.05

HHH-Alignment and MT-bench human judgements

Evaluator LMHHH ALIGNMENTMT BENCH HUMAN JUDG .
Help .Harm .Hon .OtherTotal Avg .Human Preference
RANDOM505050505034.26
STANFORDNLP REWARD MODEL69.4960.3452.4651.1658.8244.79
ALMOST REWARD MODEL74.5867.2478.6986.0576.0249.9
LLAMA2 -CHAT 7B66.181.0370.4974.4272.8551.78
LLAMA2 -CHAT 13B74.5887.9355.7479.0773.7652.34
LLAMA2 -CHAT 70B66.189.6667.2174.4274.2153.67
LLAMA2 -CHAT 13B+COARSE .68.7468.9765.5767.4467.4246.89
GPT -3.5-TURBO -061376.2787.9367.2186.0578.7357.12
PROMETHEUS 7B69.4984.4878.6990.780.0955.14
PROMETHEUS 13B81.3682.7675.4176.7479.1957.72
UltraRM (13B)86.4479.3181.9788.3783.7156
PairRM (0.4B)84.7584.4880.3390.784.6259
GPT -4-061391.5393.185.2583.7288.6963.87

While PairRM is a extremely small model (0.4B) based on deberta, the pairwise comparison aggrement performance approches GPT-4's performance!

Two reasons to attribute:

  • Our PairRM specically designed model arch for pairwise comparison through bidirectional attention (See LLM-blender paper for more details)
  • The high-quality and large-scale human preference annotation data it was train on (see training dataset list on this hugging face page)

Citation & Credits

If you are using PairRM in your research, please cite LLM-blender.

@inproceedings{llm-blender-2023,
    title = "LLM-Blender: Ensembling Large Language Models with Pairwise Comparison and Generative Fusion",
    author = "Jiang, Dongfu and Ren, Xiang and Lin, Bill Yuchen",
    booktitle = "Proceedings of the 61th Annual Meeting of the Association for Computational Linguistics (ACL 2023)",
    year = "2023"
}

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм

Нельзя запустить

Для архитектуры deberta нет загрузчика под задачу llm.

Ревизия весов
5b880cc

0 моделей