dhanilka commited on
Commit
51ab084
1 Parent(s): 0329a44

Create app.py

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