/ Модель

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

Контекст
32 768 токенов
Параметры
7,1 млрд
Размер весов
15,2 ГБ
Лицензия
CC BY 4.0
Архитектура
qwen2 · dense
Базовая модель
Qwen2-7B-Instruct
Опубликована
2 сен 2024

Hammer-7b

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

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

44скачиваний за 30 дней9лайковвеса обновлены9 окт 2024

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Hammer-7b — языковая модель MadeAgents, дообученная на Qwen2-7B-Instruct с применением техники function masking для повышения точности вызова функций ИИ-агентами. Модель содержит 7,1 млрд параметров, использует плотную архитектуру Qwen2 и принимает текстовые запросы, выдавая текст с вызовами функций в подходящем сценарии интеграции. Контекст — до 32 768 токенов.

Модель предназначена для агентных приложений, которым нужно выбирать и вызывать инструменты или API, в том числе локально и на устройствах с ограниченными ресурсами. В README описано обучение на данных APIGen Function Calling и наборах Salesforce/xlam-function-calling-60k и MadeAgents/xlam-irrelevance-7.5k, а также оценки на бенчмарках вызова функций. Распространяется по лицензии CC BY 4.0. Заявленные результаты бенчмарков не гарантируют качество в конкретном приложении; модель требует интеграции с обработчиком функций и проверки генерируемых вызовов.

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

  • Выбор функции или API для выполнения запроса пользователя
  • Формирование структурированных вызовов инструментов для ИИ-агента
  • Подключение локального языкового агента к прикладным API
  • Обработка запросов, где нужно определить, следует ли вызывать инструмент
  • Создание агентных приложений для устройств с ограниченными ресурсами

Ограничения

Для выполнения действий требуется внешняя интеграция с функциями или API; сгенерированные вызовы следует проверять перед исполнением. Оценки на бенчмарках из README не гарантируют аналогичного качества на пользовательских сценариях.

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

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

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

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

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

Открыть на Hugging Face

Hammer-7b Function Calling Model

[Updates!!!] Hammer 2.0 Series have been Published

We're excited to release lightweight Hammer 2.0 models (0.5B , 1.5B , 3B , and 7B) with strong function calling capability, which empower developers to build personalized, on-device agentic applications.

Introduction

Hammer is a series of cutting-edge Large Language Models (LLMs) crafted to boost the critical capability of AI agents: function calling. Differing from existing models focusing on training data refinement, Hammer optimizes performance primarily through advanced training techniques. Focusing on on-device applications, we release a number of models from 1.5B, 4B to 7B parameters.

Model Details

Hammer finetuned based on Qwen 2.0 series using function masking techniques. It's trained using the APIGen Function Calling Datasets containing 60,000 samples, supplemented by xlam-irrelevance-7.5k we generated. Hammer has achieved exceptional performances across numerous function calling benchmarks. For more details, please refer to Hammer: Robust Function-Calling for On-Device Language Models via Function Masking and Hammer GitHub repository.

Evaluation

First, we evaluate Hammer series on the Berkeley Function-Calling Leaderboard (BFCL-v2):

The above table indicates that within the BFCL framework, our Hammer series consistently achieves corresponding sota performance at comparable scales, particularly Hammer-7B, whose overall performance ranks second only to the proprietary GPT-4.

In addition, we evaluated our Hammer series (1.5b, 4b, 7b) on other academic benchmarks to further show our model's generalization ability:

Hammer models showcase highly stable performance, suggesting the robustness of Hammer series. In contrast, the baseline approaches display varying levels of effectiveness.

Requiements

The code of Hammer-7b has been in the latest Hugging face transformers and we advise you to install transformers>=4.37.0.

How to Use

This is a simple example of how to use our model.

import json
import torch 
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "MadeAgents/Hammer-7b"
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name) 

# Please use our provided instruction prompt for best performance
TASK_INSTRUCTION = """You are a tool calling assistant. In order to complete the user's request, you need to select one or more appropriate tools from the following tools and fill in the correct values for the tool parameters. Your specific tasks are:
1. Make one or more function/tool calls to meet the request based on the question.
2. If none of the function can be used, point it out and refuse to answer.
3. If the given question lacks the parameters required by the function, also point it out.
"""

FORMAT_INSTRUCTION = """
The output MUST strictly adhere to the following JSON format, and NO other text MUST be included.
The example format is as follows. Please make sure the parameter type is correct. If no function call is needed, please directly output an empty list '[]'
```
[
    {"name": "func_name1", "arguments": {"argument1": "value1", "argument2": "value2"}},
    ... (more tool calls as required)
]
```
"""

# Define the input query and available tools
query = "Where can I find live giveaways for beta access and games? And what's the weather like in New York, US?" 

live_giveaways_by_type = {
    "name": "live_giveaways_by_type",
    "description": "Retrieve live giveaways from the GamerPower API based on the specified type.",
    "parameters": {
        "type": "object",
        "properties": {
            "type": {
                "type": "string",
                "description": "The type of giveaways to retrieve (e.g., game, loot, beta).",
                "default": "game"
            }
        },
        "required": ["type"]
    }
}
get_current_weather={
        "name": "get_current_weather",
        "description": "Get the current weather",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA"
                }
            },
            "required": ["location"]
        }
    }
get_stock_price={
        "name": "get_stock_price",
        "description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.",
        "parameters": {
            "type": "object",
            "properties": {
                "ticker": {
                    "type": "string",
                    "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
                }
            },
            "required": ["ticker"]
        }
    }

def convert_to_format_tool(tools):
    ''''''
    if isinstance(tools, dict):
        format_tools = {
            "name": tools["name"],
            "description": tools["description"],
            "parameters": tools["parameters"].get("properties", {}),
        }
        required = tools["parameters"].get("required", [])
        for param in required:
            format_tools["parameters"][param]["required"] = True
        for param in format_tools["parameters"].keys():
            if "default" in format_tools["parameters"][param]:
                default = format_tools["parameters"][param]["default"]
                format_tools["parameters"][param]["description"]+=f"default is \'{default}\'"
        return format_tools
    elif isinstance(tools, list):
        return [convert_to_format_tool(tool) for tool in tools]
    else:
        return tools
# Helper function to build the input prompt for our model
def build_prompt(task_instruction: str, format_instruction: str, tools: list, query: str):
    prompt = f"[BEGIN OF TASK INSTRUCTION]\n{task_instruction}\n[END OF TASK INSTRUCTION]\n\n"
    prompt += f"[BEGIN OF AVAILABLE TOOLS]\n{json.dumps(tools)}\n[END OF AVAILABLE TOOLS]\n\n"
    prompt += f"[BEGIN OF FORMAT INSTRUCTION]\n{format_instruction}\n[END OF FORMAT INSTRUCTION]\n\n"
    prompt += f"[BEGIN OF QUERY]\n{query}\n[END OF QUERY]\n\n"
    return prompt
   
# Build the input and start the inference
openai_format_tools = [live_giveaways_by_type, get_current_weather,get_stock_price]
format_tools = convert_to_format_tool(openai_format_tools)
content = build_prompt(TASK_INSTRUCTION, FORMAT_INSTRUCTION, format_tools, query)

messages=[
    { 'role': 'user', 'content': content}
]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)

# tokenizer.eos_token_id is the id of <|EOT|> token
outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)
print(tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True))

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей