loubnabnl HF staff commited on
Commit
6918c89
·
verified ·
1 Parent(s): 804cbf6

Create app.py

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