/ Модель

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

Контекст
32 768 токенов
Параметры
8 млрд
Размер весов
19 ГБ
Лицензия
Apache 2.0
Архитектура
qwen2 · dense
Библиотека
transformers
Опубликована
10 июн 2024

Qwen2-7B-Instruct

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

Дообученная Qwen2-7B-Instruct для многошаговых диалогов с вызовом функций и инструментов.

25скачиваний за 30 дней6лайковвеса обновлены4 июл 2024

Бенчмарки

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

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

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

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

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

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

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

rubra-ai/Qwen2-7B-Instruct — дообученная компанией Rubra модель Qwen2-7B-Instruct для диалогов и многошагового вызова функций и инструментов. Модель основана на плотной авторегрессионной архитектуре Qwen2, содержит 8 млрд параметров и поддерживает контекст до 32 768 токенов. Она принимает текст и генерирует текстовые ответы и вызовы инструментов.

Модель предназначена для чат-ботов и агентных сценариев, где ассистент выбирает функции, передаёт им аргументы, получает результаты и продолжает диалог. В README указано, что модель прошла дополнительное постобучение с замороженными параметрами и DPO на закрытом наборе данных с примерами вызова функций, диалогов и инструкций. Заявлена лицензия Apache-2.0.

Модель может выдавать предвзятые или ошибочные ответы; результаты в чувствительных и критически важных сценариях требуют проверки. Языковые метаданные карточки указывают английский и китайский, но README не уточняет качество поддержки каждого языка.

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

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

Ограничения

Модель может выдавать предвзятые или неверные ответы, поэтому результаты в чувствительных и критически важных сценариях следует проверять. Качество поддержки отдельных языков и результаты сравнительных оценок в карточке не описаны.

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

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

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

Также подходит для

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

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

Открыть на Hugging Face

Qwen2 7B Instruct

Model description

The model is the result of further post-training Qwen/Qwen2-7B-Instruct. It is capable of complex multi-turn tool/function calling.

Training

The model was post-trained (freeze tuned & DPO) on a proprietary dataset consisting of diverse function calling, chat, and instruct data.

How to use

You can use the model with the Hugging Face transformers and the rubra library rubra-tools as follows:

pip install rubra_tools torch==2.3.0 transformers accelerate

You also need Node.js and npm installed. Once you do, install the jsonrepair package - it's used to fix some rare hallucinations by the model.

npm install jsonrepair

1. Load the Model

from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
from rubra_tools import preprocess_input, postprocess_output

model_id = "rubra-ai/Qwen2-7B-Instruct"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype="auto",
    device_map="auto",
)

2. Define Functions

Here we use 4 functions for a simple math chaining question:

functions = [
    {
            'type': 'function',
            'function': {
                'name': 'addition',
                'description': "Adds two numbers together",
                'parameters': {
                    'type': 'object',
                    'properties': {
                        'a': {
                            'description': 'First number to add',
                            'type': 'string'
                        },
                        'b': {
                            'description': 'Second number to add',
                            'type': 'string'
                        }
                    },
                    'required': []
                }
            }
        },
        {
            'type': 'function',
            'function': {
                'name': 'subtraction',
                'description': "Subtracts two numbers",
                'parameters': {
                    'type': 'object',
                    'properties': {
                        'a': {
                            'description': 'First number to be subtracted from',
                            'type': 'string'
                        },
                        'b': {
                            'description': 'Number to subtract',
                            'type': 'string'
                        }
                    },
                    'required': []
                }
            }
        },
        {
            'type': 'function',
            'function': {
                'name': 'multiplication',
                'description': "Multiply two numbers together",
                'parameters': {
                    'type': 'object',
                    'properties': {
                        'a': {
                            'description': 'First number to multiply',
                            'type': 'string'
                        },
                        'b': {
                            'description': 'Second number to multiply',
                            'type': 'string'
                        }
                    },
                    'required': []
                }
            }
        },
        {
            'type': 'function',
            'function': {
                'name': 'division',
                'description': "Divide two numbers",
                'parameters': {
                    'type': 'object',
                    'properties': {
                        'a': {
                            'description': 'First number to use as the dividend',
                            'type': 'string'
                        },
                        'b': {
                            'description': 'Second number to use as the divisor',
                            'type': 'string'
                        }
                    },
                    'required': []
                }
            }
        },
]

3. Start the conversation

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is the result of four plus six? Take the result and add 2? Then multiply by 5 and then divide by two"},
]

def run_model(messages, functions):
    ## Format messages in Rubra's format
    formatted_msgs = preprocess_input(msgs=messages, tools=functions)

    text = tokenizer.apply_chat_template(
        formatted_msgs,
        tokenize=False,
        add_generation_prompt=True
    )
    model_inputs = tokenizer([text], return_tensors="pt").to(model.device)

    generated_ids = model.generate(
        model_inputs.input_ids,
        max_new_tokens=512
    )
    generated_ids = [
        output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
    ]

    response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
    return response


raw_output = run_model(messages, functions)
# Check if there's a function call
function_call = postprocess_output(raw_output)
if function_call:
    print(function_call)
else:
    print(raw_output)

You should see this output, which is a function call made by the AI assistant:

[{'id': 'fc65a533', 'function': {'name': 'addition', 'arguments': '{"a": "4", "b": "6"}'}, 'type': 'function'}]

4. Add Executed Tool Result to Message History & Continue the Conversation

if function_call:
    # append the assistant tool call msg
    messages.append({"role": "assistant", "tool_calls": function_call})
    # append the result of the tool call in openai format, in this case, the value of add 6 to 4 is 10.
    messages.append({'role': 'tool', 'tool_call_id': function_call[0]["id"], 'name': function_call[0]["function"]["name"], 'content': '10'})
    raw_output1 = run_model(messages, functions)
    # Check if there's a function call

    function_call = postprocess_output(raw_output1)
    if function_call:
        print(function_call)
    else:
        print(raw_output)

The LLM will make another call

[{'id': '2ffc3de4', 'function': {'name': 'addition', 'arguments': '{"a": "10", "b": "2"}'}, 'type': 'function'}]

Framework Versions

  • Transformers 4.41.2
  • Pytorch 2.3.1+cu121
  • Datasets 2.19.2
  • Tokenizers 0.19.1

Limitations and Bias

While the model performs well on a wide range of tasks, it may still produce biased or incorrect outputs. Users should exercise caution and critical judgment when using the model in sensitive or high-stakes applications. The model's outputs are influenced by the data it was trained on, which may contain inherent biases.

Ethical Considerations

Users should ensure that the deployment of this model adheres to ethical guidelines and consider the potential societal impact of the generated text. Misuse of the model for generating harmful or misleading content is strongly discouraged.

Acknowledgements

We would like to thank Alibaba Cloud for the model.

Contact Information

For questions or comments about the model, please reach out to the rubra team.

Citation

If you use this work, please cite it as:

@misc {rubra_ai_2024,
	author       = { Sanjay Nadhavajhala and Yingbei Tong },
	title        = { Rubra-Qwen2-7B-Instruct },
	year         = 2024,
	url          = { https://huggingface.co/rubra-ai/Qwen2-7B-Instruct },
	doi          = { 10.57967/hf/2683 },
	publisher    = { Hugging Face }
}

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

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

GPU в ailist

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

Можно запустить

Подбираем GPU…

Класс архитектуры
Qwen2ForCausalLM
Ревизия весов
7ff5b5d

0 моделей