andrijdavid commited on
Commit
f7b0b67
·
verified ·
1 Parent(s): 394c704

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +397 -0
README.md ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ ---
4
+ language:
5
+ - en
6
+ license: llama3
7
+ tags:
8
+ - nvidia
9
+ - chatqa-1.5
10
+ - chatqa
11
+ - llama-3
12
+ - pytorch
13
+ - GGUF
14
+ pipeline_tag: text-generation
15
+ quantized_by: andrijdavid
16
+ ---
17
+ # Llama3-ChatQA-1.5-8B-GGUF
18
+ - Original model: [Llama3-ChatQA-1.5-8B](https://huggingface.co/nvidia/Llama3-ChatQA-1.5-8B)
19
+
20
+ <!-- description start -->
21
+ ## Description
22
+
23
+ This repo contains GGUF format model files for [Llama3-ChatQA-1.5-8B](https://huggingface.co/nvidia/Llama3-ChatQA-1.5-8B).
24
+
25
+ <!-- description end -->
26
+ <!-- README_GGUF.md-about-gguf start -->
27
+ ### About GGUF
28
+ GGUF is a new format introduced by the llama.cpp team on August 21st 2023. It is a replacement for GGML, which is no longer supported by llama.cpp.
29
+ Here is an incomplete list of clients and libraries that are known to support GGUF:
30
+ * [llama.cpp](https://github.com/ggerganov/llama.cpp). This is the source project for GGUF, providing both a Command Line Interface (CLI) and a server option.
31
+ * [text-generation-webui](https://github.com/oobabooga/text-generation-webui), Known as the most widely used web UI, this project boasts numerous features and powerful extensions, and supports GPU acceleration.
32
+ * [Ollama](https://github.com/jmorganca/ollama) Ollama is a lightweight and extensible framework designed for building and running language models locally. It features a simple API for creating, managing, and executing models, along with a library of pre-built models for use in various applications​
33
+ * [KoboldCpp](https://github.com/LostRuins/koboldcpp), A comprehensive web UI offering GPU acceleration across all platforms and architectures, particularly renowned for storytelling.
34
+ * [GPT4All](https://gpt4all.io), This is a free and open source GUI that runs locally, supporting Windows, Linux, and macOS with full GPU acceleration.
35
+ * [LM Studio](https://lmstudio.ai/) An intuitive and powerful local GUI for Windows and macOS (Silicon), featuring GPU acceleration.
36
+ * [LoLLMS Web UI](https://github.com/ParisNeo/lollms-webui). A notable web UI with a variety of unique features, including a comprehensive model library for easy model selection.
37
+ * [Faraday.dev](https://faraday.dev/), An attractive, user-friendly character-based chat GUI for Windows and macOS (both Silicon and Intel), also offering GPU acceleration.
38
+ * [llama-cpp-python](https://github.com/abetlen/llama-cpp-python), A Python library equipped with GPU acceleration, LangChain support, and an OpenAI-compatible API server.
39
+ * [candle](https://github.com/huggingface/candle), A Rust-based ML framework focusing on performance, including GPU support, and designed for ease of use.
40
+ * [ctransformers](https://github.com/marella/ctransformers), A Python library featuring GPU acceleration, LangChain support, and an OpenAI-compatible AI server.
41
+ * [localGPT](https://github.com/PromtEngineer/localGPT) An open-source initiative enabling private conversations with documents.
42
+ <!-- README_GGUF.md-about-gguf end -->
43
+
44
+ <!-- compatibility_gguf start -->
45
+ ## Explanation of quantisation methods
46
+ <details>
47
+ <summary>Click to see details</summary>
48
+ The new methods available are:
49
+
50
+ * GGML_TYPE_Q2_K - "type-1" 2-bit quantization in super-blocks containing 16 blocks, each block having 16 weight. Block scales and mins are quantized with 4 bits. This ends up effectively using 2.5625 bits per weight (bpw)
51
+ * GGML_TYPE_Q3_K - "type-0" 3-bit quantization in super-blocks containing 16 blocks, each block having 16 weights. Scales are quantized with 6 bits. This end up using 3.4375 bpw.
52
+ * GGML_TYPE_Q4_K - "type-1" 4-bit quantization in super-blocks containing 8 blocks, each block having 32 weights. Scales and mins are quantized with 6 bits. This ends up using 4.5 bpw.
53
+ * GGML_TYPE_Q5_K - "type-1" 5-bit quantization. Same super-block structure as GGML_TYPE_Q4_K resulting in 5.5 bpw
54
+ * GGML_TYPE_Q6_K - "type-0" 6-bit quantization. Super-blocks with 16 blocks, each block having 16 weights. Scales are quantized with 8 bits. This ends up using 6.5625 bpw.
55
+ </details>
56
+ <!-- compatibility_gguf end -->
57
+
58
+ <!-- README_GGUF.md-how-to-download start -->
59
+ ## How to download GGUF files
60
+
61
+ **Note for manual downloaders:** You almost never want to clone the entire repo! Multiple different quantisation formats are provided, and most users only want to pick and download a single folder.
62
+
63
+ The following clients/libraries will automatically download models for you, providing a list of available models to choose from:
64
+
65
+ * LM Studio
66
+ * LoLLMS Web UI
67
+ * Faraday.dev
68
+
69
+ ### In `text-generation-webui`
70
+
71
+ Under Download Model, you can enter the model repo: LiteLLMs/Llama3-ChatQA-1.5-8B-GGUF and below it, a specific filename to download, such as: Q4_0/Q4_0-00001-of-00009.gguf.
72
+
73
+ Then click Download.
74
+
75
+ ### On the command line, including multiple files at once
76
+
77
+ I recommend using the `huggingface-hub` Python library:
78
+
79
+ ```shell
80
+ pip3 install huggingface-hub
81
+ ```
82
+
83
+ Then you can download any individual model file to the current directory, at high speed, with a command like this:
84
+
85
+ ```shell
86
+ huggingface-cli download LiteLLMs/Llama3-ChatQA-1.5-8B-GGUF Q4_0/Q4_0-00001-of-00009.gguf --local-dir . --local-dir-use-symlinks False
87
+ ```
88
+
89
+ <details>
90
+ <summary>More advanced huggingface-cli download usage (click to read)</summary>
91
+
92
+ You can also download multiple files at once with a pattern:
93
+
94
+ ```shell
95
+ huggingface-cli download LiteLLMs/Llama3-ChatQA-1.5-8B-GGUF --local-dir . --local-dir-use-symlinks False --include='*Q4_K*gguf'
96
+ ```
97
+
98
+ For more documentation on downloading with `huggingface-cli`, please see: [HF -> Hub Python Library -> Download files -> Download from the CLI](https://huggingface.co/docs/huggingface_hub/guides/download#download-from-the-cli).
99
+
100
+ To accelerate downloads on fast connections (1Gbit/s or higher), install `hf_transfer`:
101
+
102
+ ```shell
103
+ pip3 install huggingface_hub[hf_transfer]
104
+ ```
105
+
106
+ And set environment variable `HF_HUB_ENABLE_HF_TRANSFER` to `1`:
107
+
108
+ ```shell
109
+ HF_HUB_ENABLE_HF_TRANSFER=1 huggingface-cli download LiteLLMs/Llama3-ChatQA-1.5-8B-GGUF Q4_0/Q4_0-00001-of-00009.gguf --local-dir . --local-dir-use-symlinks False
110
+ ```
111
+
112
+ Windows Command Line users: You can set the environment variable by running `set HF_HUB_ENABLE_HF_TRANSFER=1` before the download command.
113
+ </details>
114
+ <!-- README_GGUF.md-how-to-download end -->
115
+ <!-- README_GGUF.md-how-to-run start -->
116
+ ## Example `llama.cpp` command
117
+
118
+ Make sure you are using `llama.cpp` from commit [d0cee0d](https://github.com/ggerganov/llama.cpp/commit/d0cee0d36d5be95a0d9088b674dbb27354107221) or later.
119
+
120
+ ```shell
121
+ ./main -ngl 35 -m Q4_0/Q4_0-00001-of-00009.gguf --color -c 8192 --temp 0.7 --repeat_penalty 1.1 -n -1 -p "<PROMPT>"
122
+ ```
123
+
124
+ Change `-ngl 32` to the number of layers to offload to GPU. Remove it if you don't have GPU acceleration.
125
+
126
+ Change `-c 8192` to the desired sequence length. For extended sequence models - eg 8K, 16K, 32K - the necessary RoPE scaling parameters are read from the GGUF file and set by llama.cpp automatically. Note that longer sequence lengths require much more resources, so you may need to reduce this value.
127
+
128
+ If you want to have a chat-style conversation, replace the `-p <PROMPT>` argument with `-i -ins`
129
+
130
+ For other parameters and how to use them, please refer to [the llama.cpp documentation](https://github.com/ggerganov/llama.cpp/blob/master/examples/main/README.md)
131
+
132
+ ## How to run in `text-generation-webui`
133
+
134
+ Further instructions can be found in the text-generation-webui documentation, here: [text-generation-webui/docs/04 ‐ Model Tab.md](https://github.com/oobabooga/text-generation-webui/blob/main/docs/04%20%E2%80%90%20Model%20Tab.md#llamacpp).
135
+
136
+ ## How to run from Python code
137
+
138
+ You can use GGUF models from Python using the [llama-cpp-python](https://github.com/abetlen/llama-cpp-python) or [ctransformers](https://github.com/marella/ctransformers) libraries. Note that at the time of writing (Nov 27th 2023), ctransformers has not been updated for some time and is not compatible with some recent models. Therefore I recommend you use llama-cpp-python.
139
+
140
+ ### How to load this model in Python code, using llama-cpp-python
141
+
142
+ For full documentation, please see: [llama-cpp-python docs](https://abetlen.github.io/llama-cpp-python/).
143
+
144
+ #### First install the package
145
+
146
+ Run one of the following commands, according to your system:
147
+
148
+ ```shell
149
+ # Base ctransformers with no GPU acceleration
150
+ pip install llama-cpp-python
151
+ # With NVidia CUDA acceleration
152
+ CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama-cpp-python
153
+ # Or with OpenBLAS acceleration
154
+ CMAKE_ARGS="-DLLAMA_BLAS=ON -DLLAMA_BLAS_VENDOR=OpenBLAS" pip install llama-cpp-python
155
+ # Or with CLBLast acceleration
156
+ CMAKE_ARGS="-DLLAMA_CLBLAST=on" pip install llama-cpp-python
157
+ # Or with AMD ROCm GPU acceleration (Linux only)
158
+ CMAKE_ARGS="-DLLAMA_HIPBLAS=on" pip install llama-cpp-python
159
+ # Or with Metal GPU acceleration for macOS systems only
160
+ CMAKE_ARGS="-DLLAMA_METAL=on" pip install llama-cpp-python
161
+ # In windows, to set the variables CMAKE_ARGS in PowerShell, follow this format; eg for NVidia CUDA:
162
+ $env:CMAKE_ARGS = "-DLLAMA_OPENBLAS=on"
163
+ pip install llama-cpp-python
164
+ ```
165
+
166
+ #### Simple llama-cpp-python example code
167
+
168
+ ```python
169
+ from llama_cpp import Llama
170
+ # Set gpu_layers to the number of layers to offload to GPU. Set to 0 if no GPU acceleration is available on your system.
171
+ llm = Llama(
172
+ model_path="./Q4_0/Q4_0-00001-of-00009.gguf", # Download the model file first
173
+ n_ctx=32768, # The max sequence length to use - note that longer sequence lengths require much more resources
174
+ n_threads=8, # The number of CPU threads to use, tailor to your system and the resulting performance
175
+ n_gpu_layers=35 # The number of layers to offload to GPU, if you have GPU acceleration available
176
+ )
177
+ # Simple inference example
178
+ output = llm(
179
+ "<PROMPT>", # Prompt
180
+ max_tokens=512, # Generate up to 512 tokens
181
+ stop=["</s>"], # Example stop token - not necessarily correct for this specific model! Please check before using.
182
+ echo=True # Whether to echo the prompt
183
+ )
184
+ # Chat Completion API
185
+ llm = Llama(model_path="./Q4_0/Q4_0-00001-of-00009.gguf", chat_format="llama-2") # Set chat_format according to the model you are using
186
+ llm.create_chat_completion(
187
+ messages = [
188
+ {"role": "system", "content": "You are a story writing assistant."},
189
+ {
190
+ "role": "user",
191
+ "content": "Write a story about llamas."
192
+ }
193
+ ]
194
+ )
195
+ ```
196
+
197
+ ## How to use with LangChain
198
+
199
+ Here are guides on using llama-cpp-python and ctransformers with LangChain:
200
+
201
+ * [LangChain + llama-cpp-python](https://python.langchain.com/docs/integrations/llms/llamacpp)
202
+ * [LangChain + ctransformers](https://python.langchain.com/docs/integrations/providers/ctransformers)
203
+
204
+ <!-- README_GGUF.md-how-to-run end -->
205
+
206
+ <!-- footer end -->
207
+
208
+ <!-- original-model-card start -->
209
+ # Original model card: Llama3-ChatQA-1.5-8B
210
+
211
+
212
+
213
+ ## Model Details
214
+ 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 (1.0)](https://arxiv.org/abs/2401.10225), and it is built on top of [Llama-3 base model](https://huggingface.co/meta-llama/Meta-Llama-3-8B). 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](https://github.com/NVIDIA/Megatron-LM), we converted the checkpoints to Hugging Face format.
215
+
216
+ ## Other Resources
217
+ [Llama3-ChatQA-1.5-70B](https://huggingface.co/nvidia/Llama3-ChatQA-1.5-70B)   [Evaluation Data](https://huggingface.co/datasets/nvidia/ChatRAG-Bench)   [Training Data](https://huggingface.co/datasets/nvidia/ChatQA-Training-Data)   [Retriever](https://huggingface.co/nvidia/dragon-multiturn-query-encoder)   [Paper](https://arxiv.org/abs/2401.10225)
218
+
219
+ ## Benchmark Results
220
+ Results in [ChatRAG Bench](https://huggingface.co/datasets/nvidia/ChatRAG-Bench) are as follows:
221
+
222
+ | | ChatQA-1.0-7B | Command-R-Plus | Llama-3-instruct-70b | GPT-4-0613 | ChatQA-1.0-70B | ChatQA-1.5-8B | ChatQA-1.5-70B |
223
+ | --: | :: | :: | :--: | :: | :---: |
224
+ | Doc2Dial | 37.88 | 33.51 | 37.88 | 34.16 | 38.9 | 39.33 | 41.26 |
225
+ | QuAC | 29.69 | 34.16 | 36.96 | 40.29 | 41.82 | 39.73 | 38.82 |
226
+ | QReCC | 46.97 | 49.77 | 51.34 | 52.01 | 48.05 | 49.03 | 51.40 |
227
+ | CoQA | 76.61 | 69.71 | 76.98 | 77.42 | 78.57 | 76.46 | 78.44 |
228
+ | DoQA | 41.57 | 40.67 | 41.24 | 43.39 | 51.94 | 49.6 | 50.67 |
229
+ | ConvFinQA | 51.61 | 71.21 | 76.6 | 81.28 | 73.69 | 78.46 | 81.88 |
230
+ | SQA | 61.87 | 74.07 | 69.61 | 79.21 | 69.14 | 73.28 | 83.82 |
231
+ | TopioCQA | 45.45 | 53.77 | 49.72 | 45.09 | 50.98 | 49.96 | 55.63 |
232
+ | HybriDial* | 54.51 | 46.7 | 48.59 | 49.81 | 56.44 | 65.76 | 68.27 |
233
+ | INSCIT | 30.96 | 35.76 | 36.23 | 36.34 | 31.9 | 30.1 | 32.31 |
234
+ | Average (all) | 47.71 | 50.93 | 52.52 | 53.90 | 54.14 | 55.17 | 58.25 |
235
+ | Average (exclude HybriDial) | 46.96 | 51.40 | 52.95 | 54.35 | 53.89 | 53.99 | 57.14 |
236
+
237
+ 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 used some samples from the 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](https://huggingface.co/datasets/nvidia/ChatRAG-Bench).
238
+
239
+
240
+ ## Prompt Format
241
+ **We highly recommend that you use the prompt format we provide, as follows:**
242
+ ### when context is available
243
+ <pre>
244
+ System: {System}
245
+
246
+ {Context}
247
+
248
+ User: {Question}
249
+
250
+ Assistant: {Response}
251
+
252
+ User: {Question}
253
+
254
+ Assistant:
255
+ </pre>
256
+
257
+ ### when context is not available
258
+ <pre>
259
+ System: {System}
260
+
261
+ User: {Question}
262
+
263
+ Assistant: {Response}
264
+
265
+ User: {Question}
266
+
267
+ Assistant:
268
+ </pre>
269
+ **The content of the system's turn (i.e., {System}) for both scenarios is as follows:**
270
+ <pre>
271
+ 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.
272
+ </pre>
273
+ **Note that our ChatQA-1.5 models are optimized for the capability with context, e.g., over documents or retrieved context.**
274
+
275
+ ## How to use
276
+
277
+ ### take the whole document as context
278
+ 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.
279
+ ```python
280
+ from transformers import AutoTokenizer, AutoModelForCausalLM
281
+ import torch
282
+
283
+ model_id = "nvidia/Llama3-ChatQA-1.5-8B"
284
+
285
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
286
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
287
+
288
+ messages = [
289
+ {"role": "user", "content": "what is the percentage change of the net income from Q4 FY23 to Q4 FY24?"}
290
+ ]
291
+
292
+ 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% |"""
293
+
294
+ def get_formatted_input(messages, context):
295
+ 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."
296
+ instruction = "Please give a full and complete answer for the question."
297
+
298
+ for item in messages:
299
+ if item['role'] == "user":
300
+ ## only apply this instruction for the first user turn
301
+ item['content'] = instruction + " " + item['content']
302
+ break
303
+
304
+ conversation = '\n\n'.join(["User: " + item["content"] if item["role"] == "user" else "Assistant: " + item["content"] for item in messages]) + "\n\nAssistant:"
305
+ formatted_input = system + "\n\n" + context + "\n\n" + conversation
306
+
307
+ return formatted_input
308
+
309
+ formatted_input = get_formatted_input(messages, document)
310
+ tokenized_prompt = tokenizer(tokenizer.bos_token + formatted_input, return_tensors="pt").to(model.device)
311
+
312
+ terminators = [
313
+ tokenizer.eos_token_id,
314
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
315
+ ]
316
+
317
+ outputs = model.generate(input_ids=tokenized_prompt.input_ids, attention_mask=tokenized_prompt.attention_mask, max_new_tokens=128, eos_token_id=terminators)
318
+
319
+ response = outputs[0][tokenized_prompt.input_ids.shape[-1]:]
320
+ print(tokenizer.decode(response, skip_special_tokens=True))
321
+ ```
322
+
323
+ ### run retrieval to get top-n chunks as context
324
+ 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](https://huggingface.co/nvidia/dragon-multiturn-query-encoder) retriever which can handle conversatinoal query. In addition, we provide a few [documents](https://huggingface.co/nvidia/Llama3-ChatQA-1.5-8B/tree/main/docs) for users to play with.
325
+
326
+ ```python
327
+ from transformers import AutoTokenizer, AutoModelForCausalLM, AutoModel
328
+ import torch
329
+ import json
330
+
331
+ ## load ChatQA-1.5 tokenizer and model
332
+ model_id = "nvidia/Llama3-ChatQA-1.5-8B"
333
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
334
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
335
+
336
+ ## load retriever tokenizer and model
337
+ retriever_tokenizer = AutoTokenizer.from_pretrained('nvidia/dragon-multiturn-query-encoder')
338
+ query_encoder = AutoModel.from_pretrained('nvidia/dragon-multiturn-query-encoder')
339
+ context_encoder = AutoModel.from_pretrained('nvidia/dragon-multiturn-context-encoder')
340
+
341
+ ## prepare documents, we take landrover car manual document that we provide as an example
342
+ chunk_list = json.load(open("docs.json"))['landrover']
343
+
344
+ messages = [
345
+ {"role": "user", "content": "how to connect the bluetooth in the car?"}
346
+ ]
347
+
348
+ ### running retrieval
349
+ ## convert query into a format as follows:
350
+ ## user: {user}\nagent: {agent}\nuser: {user}
351
+ formatted_query_for_retriever = '\n'.join([turn['role'] + ": " + turn['content'] for turn in messages]).strip()
352
+
353
+ query_input = retriever_tokenizer(formatted_query_for_retriever, return_tensors='pt')
354
+ ctx_input = retriever_tokenizer(chunk_list, padding=True, truncation=True, max_length=512, return_tensors='pt')
355
+ query_emb = query_encoder(**query_input).last_hidden_state[:, 0, :]
356
+ ctx_emb = context_encoder(**ctx_input).last_hidden_state[:, 0, :]
357
+
358
+ ## Compute similarity scores using dot product and rank the similarity
359
+ similarities = query_emb.matmul(ctx_emb.transpose(0, 1)) # (1, num_ctx)
360
+ ranked_results = torch.argsort(similarities, dim=-1, descending=True) # (1, num_ctx)
361
+
362
+ ## get top-n chunks (n=5)
363
+ retrieved_chunks = [chunk_list[idx] for idx in ranked_results.tolist()[0][:5]]
364
+ context = "\n\n".join(retrieved_chunks)
365
+
366
+ ### running text generation
367
+ formatted_input = get_formatted_input(messages, context)
368
+ tokenized_prompt = tokenizer(tokenizer.bos_token + formatted_input, return_tensors="pt").to(model.device)
369
+
370
+ terminators = [
371
+ tokenizer.eos_token_id,
372
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
373
+ ]
374
+ outputs = model.generate(input_ids=tokenized_prompt.input_ids, attention_mask=tokenized_prompt.attention_mask, max_new_tokens=128, eos_token_id=terminators)
375
+
376
+ response = outputs[0][tokenized_prompt.input_ids.shape[-1]:]
377
+ print(tokenizer.decode(response, skip_special_tokens=True))
378
+ ```
379
+
380
+ ## Correspondence to
381
+ Zihan Liu (zihanl@nvidia.com), Wei Ping (wping@nvidia.com)
382
+
383
+ ## Citation
384
+ <pre>
385
+ @article{liu2024chatqa,
386
+ title={ChatQA: Building GPT-4 Level Conversational QA Models},
387
+ author={Liu, Zihan and Ping, Wei and Roy, Rajarshi and Xu, Peng and Lee, Chankyu and Shoeybi, Mohammad and Catanzaro, Bryan},
388
+ journal={arXiv preprint arXiv:2401.10225},
389
+ year={2024}}
390
+ </pre>
391
+
392
+
393
+ ## License
394
+ The use of this model is governed by the [META LLAMA 3 COMMUNITY LICENSE AGREEMENT](https://llama.meta.com/llama3/license/)
395
+
396
+
397
+ <!-- original-model-card end -->