HussnainZ commited on
Commit
b15b26f
1 Parent(s): 3e8a8b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -1
app.py CHANGED
@@ -1,3 +1,132 @@
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- gr.load("models/NousResearch/Hermes-2-Pro-Mistral-7B").launch()
 
 
1
+ pip install -U transformers
2
+ import os
3
+ from threading import Thread
4
+ from typing import Iterator
5
+
6
  import gradio as gr
7
+ import spaces
8
+ import torch
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
10
+
11
+ MAX_MAX_NEW_TOKENS = 2048
12
+ DEFAULT_MAX_NEW_TOKENS = 1024
13
+ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
14
+
15
+ DESCRIPTION = """\
16
+ # Hermes-2 Pro 7b Chat
17
+ This Space demonstrates [Hermes-2 Pro 7b](https://huggingface.co/NousResearch/Hermes-2-Pro-Mistral-7B) by Nous Research, a finetuned Mistral model with 7B parameters for chat instructions.
18
+ """
19
+
20
+
21
+ if not torch.cuda.is_available():
22
+ DESCRIPTION += "\n<p>Running on CPU! This demo does not work on CPU.</p>"
23
+
24
+
25
+ if torch.cuda.is_available():
26
+ model_id = "NousResearch/Hermes-2-Pro-Mistral-7B"
27
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
28
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
29
+ tokenizer.use_default_system_prompt = False
30
+
31
+
32
+ @spaces.GPU(enable_queue=True, duration=90)
33
+ def generate(
34
+ message: str,
35
+ chat_history: list[tuple[str, str]],
36
+ system_prompt: str,
37
+ max_new_tokens: int = 1300,
38
+ temperature: float = 0.4,
39
+ top_p: float = 0.9,
40
+ top_k: int = 50,
41
+ repetition_penalty: float = 1.2,
42
+ ) -> Iterator[str]:
43
+ conversation = []
44
+ if system_prompt:
45
+ conversation.append({"role": "system", "content": system_prompt})
46
+ for user, assistant in chat_history:
47
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
48
+ conversation.append({"role": "user", "content": message})
49
+
50
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
51
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
52
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
53
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
54
+ input_ids = input_ids.to(model.device)
55
+
56
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
57
+ generate_kwargs = dict(
58
+ {"input_ids": input_ids},
59
+ streamer=streamer,
60
+ max_new_tokens=max_new_tokens,
61
+ do_sample=True,
62
+ top_p=top_p,
63
+ top_k=top_k,
64
+ temperature=temperature,
65
+ num_beams=1,
66
+ repetition_penalty=repetition_penalty,
67
+ )
68
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
69
+ t.start()
70
+
71
+ outputs = []
72
+ for text in streamer:
73
+ outputs.append(text)
74
+ yield "".join(outputs)
75
+
76
+
77
+ chat_interface = gr.ChatInterface(
78
+ fn=generate,
79
+ additional_inputs=[
80
+ gr.Textbox(label="System prompt", lines=6),
81
+ gr.Slider(
82
+ label="Max new tokens",
83
+ minimum=1,
84
+ maximum=MAX_MAX_NEW_TOKENS,
85
+ step=1,
86
+ value=DEFAULT_MAX_NEW_TOKENS,
87
+ ),
88
+ gr.Slider(
89
+ label="Temperature",
90
+ minimum=0.1,
91
+ maximum=4.0,
92
+ step=0.1,
93
+ value=0.6,
94
+ ),
95
+ gr.Slider(
96
+ label="Top-p (nucleus sampling)",
97
+ minimum=0.05,
98
+ maximum=1.0,
99
+ step=0.05,
100
+ value=0.9,
101
+ ),
102
+ gr.Slider(
103
+ label="Top-k",
104
+ minimum=1,
105
+ maximum=1000,
106
+ step=1,
107
+ value=50,
108
+ ),
109
+ gr.Slider(
110
+ label="Repetition penalty",
111
+ minimum=1.0,
112
+ maximum=2.0,
113
+ step=0.05,
114
+ value=1.2,
115
+ ),
116
+ ],
117
+ stop_btn=None,
118
+ examples=[
119
+ ["Hello there! How are you doing?"],
120
+ ["Can you explain briefly to me what is the Python programming language?"],
121
+ ["Explain the plot of Cinderella in a sentence."],
122
+ ["How many hours does it take a man to eat a Helicopter?"],
123
+ ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
124
+ ],
125
+ )
126
+
127
+ with gr.Blocks(css="style.css") as demo:
128
+ gr.Markdown(DESCRIPTION)
129
+ chat_interface.render()
130
 
131
+ if __name__ == "__main__":
132
+ demo.queue(max_size=20).launch()