/ Модель

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

Контекст
8 192 токена
Параметры
7,5 млрд
Размер весов
16,1 ГБ
Лицензия
Llama 3
Архитектура
llama · dense
Опубликована
28 апр 2024

Llama3-ChatQA-1.5-8B

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

Разговорная модель NVIDIA на базе Llama 3 для ответов на вопросы по документам и контексту в сценариях RAG.

11 874скачиваний за 30 дней556лайковвеса обновлены24 мая 2024

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Llama3-ChatQA-1.5-8B — разговорная языковая модель NVIDIA для ответов на вопросы и систем генерации с дополнением извлечёнными данными (RAG). Она дообучена на базе Llama 3 с улучшенной методикой ChatQA и дополнительными данными для разговорных вопросов, табличных запросов и арифметических вычислений. Модель имеет плотную архитектуру LlamaForCausalLM, около 7,5 млрд параметров и контекст до 8192 токенов; репозиторий содержит веса в формате Safetensors.

Модель рассчитана прежде всего на ответы по предоставленному контексту: это могут быть целые документы, помещающиеся в контекст, или найденные поиском фрагменты. Она поддерживает разговорный формат и ориентирована на английский язык. В README приведены результаты оценки на наборах разговорного QA и RAG; качество зависит от контекста и сценария, поэтому ответы следует проверять, особенно при вычислениях и работе с таблицами. Лицензия — Llama 3 License.

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

  • ответы на вопросы по внутренним документам
  • разговорный поиск по длинным документам через RAG
  • ответы на последовательные уточняющие вопросы по контексту
  • извлечение ответов из таблиц
  • арифметические вычисления в диалоге

Ограничения

Оптимизирована для ответов с предоставленным контекстом, а не для самостоятельного поиска документов; качество ответов и вычислений может зависеть от полноты контекста и требует проверки.

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

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

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

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

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

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

Открыть на Hugging Face

Model Details

We introduce Llama3-ChatQA-1.5, which excels at conversational question answering (QA) and retrieval-augmented generation (RAG). Llama3-ChatQA-1.5 is developed using an improved training recipe from ChatQA paper, and it is built on top of Llama-3 base model. Specifically, we incorporate more conversational QA data to enhance its tabular and arithmetic calculation capability. Llama3-ChatQA-1.5 has two variants: Llama3-ChatQA-1.5-8B and Llama3-ChatQA-1.5-70B. Both models were originally trained using Megatron-LM, we converted the checkpoints to Hugging Face format. For more information about ChatQA, check the website!

Other Resources

Llama3-ChatQA-1.5-70B   Evaluation Data   Training Data   Retriever   Website   Paper

Benchmark Results

Results in ChatRAG Bench are as follows:

ChatQA-1.0-7BCommand-R-PlusLlama3-instruct-70bGPT-4-0613GPT-4-TurboChatQA-1.0-70BChatQA-1.5-8BChatQA-1.5-70B
Doc2Dial37.8833.5137.8834.1635.3538.9039.3341.26
QuAC29.6934.1636.9640.2940.1041.8239.7338.82
QReCC46.9749.7751.3452.0151.4648.0549.0351.40
CoQA76.6169.7176.9877.4277.7378.5776.4678.44
DoQA41.5740.6741.2443.3941.6051.9449.6050.67
ConvFinQA51.6171.2176.681.2884.1673.6978.4681.88
SQA61.8774.0769.6179.2179.9869.1473.2883.82
TopioCQA45.4553.7749.7245.0948.3250.9849.9655.63
HybriDial*54.5146.748.5949.8147.8656.4465.7668.27
INSCIT30.9635.7636.2336.3433.7531.9030.1032.31
Average (all)47.7150.9352.5253.9054.0354.1455.1758.25
Average (exclude HybriDial)46.9651.4052.9554.3554.7253.8953.9957.14

Note that ChatQA-1.5 is built based on Llama-3 base model, and ChatQA-1.0 is built based on Llama-2 base model. ChatQA-1.5 models use HybriDial training dataset. To ensure fair comparison, we also compare average scores excluding HybriDial. The data and evaluation scripts for ChatRAG Bench can be found here.

Prompt Format

We highly recommend that you use the prompt format we provide, as follows:

when context is available

when context is not available

The content of the system's turn (i.e., {System}) for both scenarios is as follows:

Note that our ChatQA-1.5 models are optimized for the capability with context, e.g., over documents or retrieved context.

How to use

take the whole document as context

This can be applied to the scenario where the whole document can be fitted into the model, so that there is no need to run retrieval over the document.

from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

model_id = "nvidia/Llama3-ChatQA-1.5-8B"

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

messages = [
    {"role": "user", "content": "what is the percentage change of the net income from Q4 FY23 to Q4 FY24?"}
]

document = """NVIDIA (NASDAQ: NVDA) today reported revenue for the fourth quarter ended January 28, 2024, of $22.1 billion, up 22% from the previous quarter and up 265% from a year ago.\nFor the quarter, GAAP earnings per diluted share was $4.93, up 33% from the previous quarter and up 765% from a year ago. Non-GAAP earnings per diluted share was $5.16, up 28% from the previous quarter and up 486% from a year ago.\nQ4 Fiscal 2024 Summary\nGAAP\n| $ in millions, except earnings per share | Q4 FY24 | Q3 FY24 | Q4 FY23 | Q/Q | Y/Y |\n| Revenue | $22,103 | $18,120 | $6,051 | Up 22% | Up 265% |\n| Gross margin | 76.0% | 74.0% | 63.3% | Up 2.0 pts | Up 12.7 pts |\n| Operating expenses | $3,176 | $2,983 | $2,576 | Up 6% | Up 23% |\n| Operating income | $13,615 | $10,417 | $1,257 | Up 31% | Up 983% |\n| Net income | $12,285 | $9,243 | $1,414 | Up 33% | Up 769% |\n| Diluted earnings per share | $4.93 | $3.71 | $0.57 | Up 33% | Up 765% |"""

def get_formatted_input(messages, context):
    system = "System: This is a chat between a user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions based on the context. The assistant should also indicate when the answer cannot be found in the context."
    instruction = "Please give a full and complete answer for the question."

    for item in messages:
        if item['role'] == "user":
            ## only apply this instruction for the first user turn
            item['content'] = instruction + " " + item['content']
            break

    conversation = '\n\n'.join(["User: " + item["content"] if item["role"] == "user" else "Assistant: " + item["content"] for item in messages]) + "\n\nAssistant:"
    formatted_input = system + "\n\n" + context + "\n\n" + conversation
    
    return formatted_input

formatted_input = get_formatted_input(messages, document)
tokenized_prompt = tokenizer(tokenizer.bos_token + formatted_input, return_tensors="pt").to(model.device)

terminators = [
    tokenizer.eos_token_id,
    tokenizer.convert_tokens_to_ids("<|eot_id|>")
]

outputs = model.generate(input_ids=tokenized_prompt.input_ids, attention_mask=tokenized_prompt.attention_mask, max_new_tokens=128, eos_token_id=terminators)

response = outputs[0][tokenized_prompt.input_ids.shape[-1]:]
print(tokenizer.decode(response, skip_special_tokens=True))

run retrieval to get top-n chunks as context

This can be applied to the scenario when the document is very long, so that it is necessary to run retrieval. Here, we use our Dragon-multiturn retriever which can handle conversatinoal query. In addition, we provide a few documents for users to play with.

from transformers import AutoTokenizer, AutoModelForCausalLM, AutoModel
import torch
import json

## load ChatQA-1.5 tokenizer and model
model_id = "nvidia/Llama3-ChatQA-1.5-8B"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")

## load retriever tokenizer and model
retriever_tokenizer = AutoTokenizer.from_pretrained('nvidia/dragon-multiturn-query-encoder')
query_encoder = AutoModel.from_pretrained('nvidia/dragon-multiturn-query-encoder')
context_encoder = AutoModel.from_pretrained('nvidia/dragon-multiturn-context-encoder')

## prepare documents, we take landrover car manual document that we provide as an example
chunk_list = json.load(open("docs.json"))['landrover']

messages = [
    {"role": "user", "content": "how to connect the bluetooth in the car?"}
]

### running retrieval
## convert query into a format as follows:
## user: {user}\nagent: {agent}\nuser: {user}
formatted_query_for_retriever = '\n'.join([turn['role'] + ": " + turn['content'] for turn in messages]).strip()

query_input = retriever_tokenizer(formatted_query_for_retriever, return_tensors='pt')
ctx_input = retriever_tokenizer(chunk_list, padding=True, truncation=True, max_length=512, return_tensors='pt')
query_emb = query_encoder(**query_input).last_hidden_state[:, 0, :]
ctx_emb = context_encoder(**ctx_input).last_hidden_state[:, 0, :]

## Compute similarity scores using dot product and rank the similarity
similarities = query_emb.matmul(ctx_emb.transpose(0, 1)) # (1, num_ctx)
ranked_results = torch.argsort(similarities, dim=-1, descending=True) # (1, num_ctx)

## get top-n chunks (n=5)
retrieved_chunks = [chunk_list[idx] for idx in ranked_results.tolist()[0][:5]]
context = "\n\n".join(retrieved_chunks)

### running text generation
formatted_input = get_formatted_input(messages, context)
tokenized_prompt = tokenizer(tokenizer.bos_token + formatted_input, return_tensors="pt").to(model.device)

terminators = [
    tokenizer.eos_token_id,
    tokenizer.convert_tokens_to_ids("<|eot_id|>")
]
outputs = model.generate(input_ids=tokenized_prompt.input_ids, attention_mask=tokenized_prompt.attention_mask, max_new_tokens=128, eos_token_id=terminators)

response = outputs[0][tokenized_prompt.input_ids.shape[-1]:]
print(tokenizer.decode(response, skip_special_tokens=True))

Correspondence to

Zihan Liu (zihanl@nvidia.com), Wei Ping (wping@nvidia.com)

Citation

License

The use of this model is governed by the META LLAMA 3 COMMUNITY LICENSE AGREEMENT

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
LlamaForCausalLM
Ревизия весов
3b98162

0 моделей