Spaces:
Paused
Paused
LeoYu
commited on
Commit
·
6c3bb74
1
Parent(s):
5b351de
support 70b
Browse files
README.md
CHANGED
@@ -11,6 +11,14 @@ license: other
|
|
11 |
suggested_hardware: a10g-small
|
12 |
---
|
13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
# LLAMA v2 Models
|
15 |
|
16 |
Llama v2 was introduced in [this paper](https://arxiv.org/abs/2307.09288).
|
|
|
11 |
suggested_hardware: a10g-small
|
12 |
---
|
13 |
|
14 |
+
# Llama 2 chatbot (Della)
|
15 |
+
|
16 |
+
This is a minimal chatbot built based on https://huggingface.co/spaces/huggingface-projects/llama-2-13b-chat
|
17 |
+
|
18 |
+
It is modified because Della does not provide internet access to its compute nodes.
|
19 |
+
|
20 |
+
Below is the original README.
|
21 |
+
|
22 |
# LLAMA v2 Models
|
23 |
|
24 |
Llama v2 was introduced in [this paper](https://arxiv.org/abs/2307.09288).
|
app.py
CHANGED
@@ -3,7 +3,11 @@ from typing import Iterator
|
|
3 |
import gradio as gr
|
4 |
import torch
|
5 |
|
6 |
-
from
|
|
|
|
|
|
|
|
|
7 |
|
8 |
DEFAULT_SYSTEM_PROMPT = """\
|
9 |
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\
|
@@ -12,24 +16,30 @@ MAX_MAX_NEW_TOKENS = 2048
|
|
12 |
DEFAULT_MAX_NEW_TOKENS = 1024
|
13 |
MAX_INPUT_TOKEN_LENGTH = 4000
|
14 |
|
15 |
-
DESCRIPTION = """
|
16 |
-
|
17 |
|
18 |
-
|
|
|
19 |
|
20 |
-
|
|
|
21 |
|
22 |
-
|
23 |
-
🐇 For a smaller model that you can run on many GPUs, check our [7B model demo](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat).
|
24 |
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
-
LICENSE = """
|
28 |
<p/>
|
29 |
|
30 |
---
|
31 |
-
As a derivate work of [Llama-2-
|
32 |
-
this demo is governed by the original [license](https://huggingface.co/spaces/huggingface-projects/llama-2-
|
33 |
"""
|
34 |
|
35 |
if not torch.cuda.is_available():
|
@@ -68,7 +78,7 @@ def generate(
|
|
68 |
raise ValueError
|
69 |
|
70 |
history = history_with_input[:-1]
|
71 |
-
generator = run(message, history, system_prompt, max_new_tokens, temperature, top_p, top_k)
|
72 |
try:
|
73 |
first_response = next(generator)
|
74 |
yield history + [(message, first_response)]
|
@@ -86,7 +96,7 @@ def process_example(message: str) -> tuple[str, list[tuple[str, str]]]:
|
|
86 |
|
87 |
|
88 |
def check_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> None:
|
89 |
-
input_token_length = get_input_token_length(message, chat_history, system_prompt)
|
90 |
if input_token_length > MAX_INPUT_TOKEN_LENGTH:
|
91 |
raise gr.Error(f'The accumulated input is too long ({input_token_length} > {MAX_INPUT_TOKEN_LENGTH}). Clear your chat history and try again.')
|
92 |
|
@@ -160,7 +170,7 @@ with gr.Blocks(css='style.css') as demo:
|
|
160 |
inputs=textbox,
|
161 |
outputs=[textbox, chatbot],
|
162 |
fn=process_example,
|
163 |
-
cache_examples=
|
164 |
)
|
165 |
|
166 |
gr.Markdown(LICENSE)
|
@@ -277,4 +287,4 @@ with gr.Blocks(css='style.css') as demo:
|
|
277 |
api_name=False,
|
278 |
)
|
279 |
|
280 |
-
demo.queue(max_size=20).launch()
|
|
|
3 |
import gradio as gr
|
4 |
import torch
|
5 |
|
6 |
+
from model_any import LlamaModel
|
7 |
+
|
8 |
+
model_id = "meta-llama/Llama-2-70b-chat"
|
9 |
+
model_size = "70"
|
10 |
+
pipeline = LlamaModel(model_id)
|
11 |
|
12 |
DEFAULT_SYSTEM_PROMPT = """\
|
13 |
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\
|
|
|
16 |
DEFAULT_MAX_NEW_TOKENS = 1024
|
17 |
MAX_INPUT_TOKEN_LENGTH = 4000
|
18 |
|
19 |
+
DESCRIPTION = f"""
|
20 |
+
Llama-2 {model_size}B Chat
|
21 |
|
22 |
+
{model_id}
|
23 |
+
"""
|
24 |
|
25 |
+
# DESCRIPTION = """
|
26 |
+
# # Llama-2 13B Chat
|
27 |
|
28 |
+
# This Space demonstrates model [Llama-2-13b-chat](https://huggingface.co/meta-llama/Llama-2-13b-chat) by Meta, a Llama 2 model with 13B parameters fine-tuned for chat instructions. Feel free to play with it, or duplicate to run generations without a queue! If you want to run your own service, you can also [deploy the model on Inference Endpoints](https://huggingface.co/inference-endpoints).
|
|
|
29 |
|
30 |
+
# 🔎 For more details about the Llama 2 family of models and how to use them with `transformers`, take a look [at our blog post](https://huggingface.co/blog/llama2).
|
31 |
+
|
32 |
+
# 🔨 Looking for an even more powerful model? Check out the large [**70B** model demo](https://huggingface.co/spaces/ysharma/Explore_llamav2_with_TGI).
|
33 |
+
# 🐇 For a smaller model that you can run on many GPUs, check our [7B model demo](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat).
|
34 |
+
|
35 |
+
# """
|
36 |
|
37 |
+
LICENSE = f"""
|
38 |
<p/>
|
39 |
|
40 |
---
|
41 |
+
As a derivate work of [Llama-2-{model_size}b-chat](https://huggingface.co/meta-llama/Llama-2-{model_size}b-chat) by Meta,
|
42 |
+
this demo is governed by the original [license](https://huggingface.co/spaces/huggingface-projects/llama-2-{model_size}b-chat/blob/main/LICENSE.txt) and [acceptable use policy](https://huggingface.co/spaces/huggingface-projects/llama-2-{model_size}b-chat/blob/main/USE_POLICY.md).
|
43 |
"""
|
44 |
|
45 |
if not torch.cuda.is_available():
|
|
|
78 |
raise ValueError
|
79 |
|
80 |
history = history_with_input[:-1]
|
81 |
+
generator = pipeline.run(message, history, system_prompt, max_new_tokens, temperature, top_p, top_k)
|
82 |
try:
|
83 |
first_response = next(generator)
|
84 |
yield history + [(message, first_response)]
|
|
|
96 |
|
97 |
|
98 |
def check_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> None:
|
99 |
+
input_token_length = pipeline.get_input_token_length(message, chat_history, system_prompt)
|
100 |
if input_token_length > MAX_INPUT_TOKEN_LENGTH:
|
101 |
raise gr.Error(f'The accumulated input is too long ({input_token_length} > {MAX_INPUT_TOKEN_LENGTH}). Clear your chat history and try again.')
|
102 |
|
|
|
170 |
inputs=textbox,
|
171 |
outputs=[textbox, chatbot],
|
172 |
fn=process_example,
|
173 |
+
cache_examples=False,
|
174 |
)
|
175 |
|
176 |
gr.Markdown(LICENSE)
|
|
|
287 |
api_name=False,
|
288 |
)
|
289 |
|
290 |
+
demo.queue(max_size=20).launch(share=True)
|
model.py
CHANGED
@@ -4,71 +4,73 @@ from typing import Iterator
|
|
4 |
import torch
|
5 |
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
6 |
|
7 |
-
|
|
|
|
|
8 |
|
9 |
-
if torch.cuda.is_available():
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
else:
|
20 |
-
|
21 |
-
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
22 |
|
23 |
|
24 |
-
def get_prompt(message: str, chat_history: list[tuple[str, str]],
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
|
37 |
|
38 |
-
def get_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> int:
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
|
43 |
|
44 |
-
def run(message: str,
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
|
|
4 |
import torch
|
5 |
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
6 |
|
7 |
+
class LlamaModel:
|
8 |
+
def __init__(self, model_id: str):
|
9 |
+
self.model_id = model_id
|
10 |
|
11 |
+
if torch.cuda.is_available():
|
12 |
+
config = AutoConfig.from_pretrained(model_id)
|
13 |
+
config.pretraining_tp = 1
|
14 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
15 |
+
model_id,
|
16 |
+
config=config,
|
17 |
+
torch_dtype=torch.float16,
|
18 |
+
load_in_4bit=False,
|
19 |
+
device_map='auto'
|
20 |
+
)
|
21 |
+
else:
|
22 |
+
self.model = None
|
23 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_id)
|
24 |
|
25 |
|
26 |
+
def get_prompt(self, message: str, chat_history: list[tuple[str, str]],
|
27 |
+
system_prompt: str) -> str:
|
28 |
+
texts = [f'<s>[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n']
|
29 |
+
# The first user input is _not_ stripped
|
30 |
+
do_strip = False
|
31 |
+
for user_input, response in chat_history:
|
32 |
+
user_input = user_input.strip() if do_strip else user_input
|
33 |
+
do_strip = True
|
34 |
+
texts.append(f'{user_input} [/INST] {response.strip()} </s><s>[INST] ')
|
35 |
+
message = message.strip() if do_strip else message
|
36 |
+
texts.append(f'{message} [/INST]')
|
37 |
+
return ''.join(texts)
|
38 |
|
39 |
|
40 |
+
def get_input_token_length(self, message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> int:
|
41 |
+
prompt = self.get_prompt(message, chat_history, system_prompt)
|
42 |
+
input_ids = self.tokenizer([prompt], return_tensors='np', add_special_tokens=False)['input_ids']
|
43 |
+
return input_ids.shape[-1]
|
44 |
|
45 |
|
46 |
+
def run(self, message: str,
|
47 |
+
chat_history: list[tuple[str, str]],
|
48 |
+
system_prompt: str,
|
49 |
+
max_new_tokens: int = 1024,
|
50 |
+
temperature: float = 0.8,
|
51 |
+
top_p: float = 0.95,
|
52 |
+
top_k: int = 50) -> Iterator[str]:
|
53 |
+
prompt = self.get_prompt(message, chat_history, system_prompt)
|
54 |
+
inputs = self.tokenizer([prompt], return_tensors='pt', add_special_tokens=False).to('cuda')
|
55 |
|
56 |
+
streamer = TextIteratorStreamer(self.tokenizer,
|
57 |
+
timeout=10.,
|
58 |
+
skip_prompt=True,
|
59 |
+
skip_special_tokens=True)
|
60 |
+
generate_kwargs = dict(
|
61 |
+
inputs,
|
62 |
+
streamer=streamer,
|
63 |
+
max_new_tokens=max_new_tokens,
|
64 |
+
do_sample=True,
|
65 |
+
top_p=top_p,
|
66 |
+
top_k=top_k,
|
67 |
+
temperature=temperature,
|
68 |
+
num_beams=1,
|
69 |
+
)
|
70 |
+
t = Thread(target=self.model.generate, kwargs=generate_kwargs)
|
71 |
+
t.start()
|
72 |
|
73 |
+
outputs = []
|
74 |
+
for text in streamer:
|
75 |
+
outputs.append(text)
|
76 |
+
yield ''.join(outputs)
|