vivekkumarbarman commited on
Commit
5db55e8
β€’
1 Parent(s): 8da05e3

Upload 2 files

Browse files
Files changed (2) hide show
  1. guanaco_7b_demo_colab.py +298 -0
  2. requirements.txt +6 -0
guanaco_7b_demo_colab.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Load the model.
2
+ # Note: It can take a while to download LLaMA and add the adapter modules.
3
+ # You can also use the 13B model by loading in 4bits.
4
+
5
+ import torch
6
+ from peft import PeftModel
7
+ from transformers import AutoModelForCausalLM, AutoTokenizer, LlamaTokenizer, StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer
8
+
9
+ model_name = "decapoda-research/llama-7b-hf"
10
+ adapters_name = 'timdettmers/guanaco-7b'
11
+
12
+ print(f"Starting to load the model {model_name} into memory")
13
+
14
+ m = AutoModelForCausalLM.from_pretrained(
15
+ model_name,
16
+ #load_in_4bit=True,
17
+ torch_dtype=torch.bfloat16,
18
+ device_map={"": 0}
19
+ )
20
+ m = PeftModel.from_pretrained(m, adapters_name)
21
+ m = m.merge_and_unload()
22
+ tok = LlamaTokenizer.from_pretrained(model_name)
23
+ tok.bos_token_id = 1
24
+
25
+ stop_token_ids = [0]
26
+
27
+ print(f"Successfully loaded the model {model_name} into memory")
28
+
29
+ # Setup the gradio Demo.
30
+
31
+ import datetime
32
+ import os
33
+ from threading import Event, Thread
34
+ from uuid import uuid4
35
+
36
+ import gradio as gr
37
+ import requests
38
+
39
+ max_new_tokens = 1536
40
+ start_message = """A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions."""
41
+
42
+ class StopOnTokens(StoppingCriteria):
43
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
44
+ for stop_id in stop_token_ids:
45
+ if input_ids[0][-1] == stop_id:
46
+ return True
47
+ return False
48
+
49
+
50
+ def convert_history_to_text(history):
51
+ text = start_message + "".join(
52
+ [
53
+ "".join(
54
+ [
55
+ f"### Human: {item[0]}\n",
56
+ f"### Assistant: {item[1]}\n",
57
+ ]
58
+ )
59
+ for item in history[:-1]
60
+ ]
61
+ )
62
+ text += "".join(
63
+ [
64
+ "".join(
65
+ [
66
+ f"### Human: {history[-1][0]}\n",
67
+ f"### Assistant: {history[-1][1]}\n",
68
+ ]
69
+ )
70
+ ]
71
+ )
72
+ return text
73
+
74
+
75
+ def log_conversation(conversation_id, history, messages, generate_kwargs):
76
+ logging_url = os.getenv("LOGGING_URL", None)
77
+ if logging_url is None:
78
+ return
79
+
80
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
81
+
82
+ data = {
83
+ "conversation_id": conversation_id,
84
+ "timestamp": timestamp,
85
+ "history": history,
86
+ "messages": messages,
87
+ "generate_kwargs": generate_kwargs,
88
+ }
89
+
90
+ try:
91
+ requests.post(logging_url, json=data)
92
+ except requests.exceptions.RequestException as e:
93
+ print(f"Error logging conversation: {e}")
94
+
95
+
96
+ def user(message, history):
97
+ # Append the user's message to the conversation history
98
+ return "", history + [[message, ""]]
99
+
100
+
101
+ def bot(history, temperature, top_p, top_k, repetition_penalty, conversation_id):
102
+ print(f"history: {history}")
103
+ # Initialize a StopOnTokens object
104
+ stop = StopOnTokens()
105
+
106
+ # Construct the input message string for the model by concatenating the current system message and conversation history
107
+ messages = convert_history_to_text(history)
108
+
109
+ # Tokenize the messages string
110
+ input_ids = tok(messages, return_tensors="pt").input_ids
111
+ input_ids = input_ids.to(m.device)
112
+ streamer = TextIteratorStreamer(tok, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
113
+ generate_kwargs = dict(
114
+ input_ids=input_ids,
115
+ max_new_tokens=max_new_tokens,
116
+ temperature=temperature,
117
+ do_sample=temperature > 0.0,
118
+ top_p=top_p,
119
+ top_k=top_k,
120
+ repetition_penalty=repetition_penalty,
121
+ streamer=streamer,
122
+ stopping_criteria=StoppingCriteriaList([stop]),
123
+ )
124
+
125
+ stream_complete = Event()
126
+
127
+ def generate_and_signal_complete():
128
+ m.generate(**generate_kwargs)
129
+ stream_complete.set()
130
+
131
+ def log_after_stream_complete():
132
+ stream_complete.wait()
133
+ log_conversation(
134
+ conversation_id,
135
+ history,
136
+ messages,
137
+ {
138
+ "top_k": top_k,
139
+ "top_p": top_p,
140
+ "temperature": temperature,
141
+ "repetition_penalty": repetition_penalty,
142
+ },
143
+ )
144
+
145
+ t1 = Thread(target=generate_and_signal_complete)
146
+ t1.start()
147
+
148
+ t2 = Thread(target=log_after_stream_complete)
149
+ t2.start()
150
+
151
+ # Initialize an empty string to store the generated text
152
+ partial_text = ""
153
+ for new_text in streamer:
154
+ partial_text += new_text
155
+ history[-1][1] = partial_text
156
+ yield history
157
+
158
+
159
+ def get_uuid():
160
+ return str(uuid4())
161
+
162
+
163
+ with gr.Blocks(
164
+ theme=gr.themes.Soft(),
165
+ css=".disclaimer {font-variant-caps: all-small-caps;}",
166
+ ) as demo:
167
+ conversation_id = gr.State(get_uuid)
168
+ gr.Markdown(
169
+ """<h1><center>Guanaco Demo</center></h1>
170
+ """
171
+ )
172
+ chatbot = gr.Chatbot().style(height=500)
173
+ with gr.Row():
174
+ with gr.Column():
175
+ msg = gr.Textbox(
176
+ label="Chat Message Box",
177
+ placeholder="Chat Message Box",
178
+ show_label=False,
179
+ ).style(container=False)
180
+ with gr.Column():
181
+ with gr.Row():
182
+ submit = gr.Button("Submit")
183
+ stop = gr.Button("Stop")
184
+ clear = gr.Button("Clear")
185
+ with gr.Row():
186
+ with gr.Accordion("Advanced Options:", open=False):
187
+ with gr.Row():
188
+ with gr.Column():
189
+ with gr.Row():
190
+ temperature = gr.Slider(
191
+ label="Temperature",
192
+ value=0.7,
193
+ minimum=0.0,
194
+ maximum=1.0,
195
+ step=0.1,
196
+ interactive=True,
197
+ info="Higher values produce more diverse outputs",
198
+ )
199
+ with gr.Column():
200
+ with gr.Row():
201
+ top_p = gr.Slider(
202
+ label="Top-p (nucleus sampling)",
203
+ value=0.9,
204
+ minimum=0.0,
205
+ maximum=1,
206
+ step=0.01,
207
+ interactive=True,
208
+ info=(
209
+ "Sample from the smallest possible set of tokens whose cumulative probability "
210
+ "exceeds top_p. Set to 1 to disable and sample from all tokens."
211
+ ),
212
+ )
213
+ with gr.Column():
214
+ with gr.Row():
215
+ top_k = gr.Slider(
216
+ label="Top-k",
217
+ value=0,
218
+ minimum=0.0,
219
+ maximum=200,
220
+ step=1,
221
+ interactive=True,
222
+ info="Sample from a shortlist of top-k tokens β€” 0 to disable and sample from all tokens.",
223
+ )
224
+ with gr.Column():
225
+ with gr.Row():
226
+ repetition_penalty = gr.Slider(
227
+ label="Repetition Penalty",
228
+ value=1.1,
229
+ minimum=1.0,
230
+ maximum=2.0,
231
+ step=0.1,
232
+ interactive=True,
233
+ info="Penalize repetition β€” 1.0 to disable.",
234
+ )
235
+ with gr.Row():
236
+ gr.Markdown(
237
+ "Disclaimer: The model can produce factually incorrect output, and should not be relied on to produce "
238
+ "factually accurate information. The model was trained on various public datasets; while great efforts "
239
+ "have been taken to clean the pretraining data, it is possible that this model could generate lewd, "
240
+ "biased, or otherwise offensive outputs.",
241
+ elem_classes=["disclaimer"],
242
+ )
243
+ with gr.Row():
244
+ gr.Markdown(
245
+ "[Privacy policy](https://gist.github.com/samhavens/c29c68cdcd420a9aa0202d0839876dac)",
246
+ elem_classes=["disclaimer"],
247
+ )
248
+
249
+ submit_event = msg.submit(
250
+ fn=user,
251
+ inputs=[msg, chatbot],
252
+ outputs=[msg, chatbot],
253
+ queue=False,
254
+ ).then(
255
+ fn=bot,
256
+ inputs=[
257
+ chatbot,
258
+ temperature,
259
+ top_p,
260
+ top_k,
261
+ repetition_penalty,
262
+ conversation_id,
263
+ ],
264
+ outputs=chatbot,
265
+ queue=True,
266
+ )
267
+ submit_click_event = submit.click(
268
+ fn=user,
269
+ inputs=[msg, chatbot],
270
+ outputs=[msg, chatbot],
271
+ queue=False,
272
+ ).then(
273
+ fn=bot,
274
+ inputs=[
275
+ chatbot,
276
+ temperature,
277
+ top_p,
278
+ top_k,
279
+ repetition_penalty,
280
+ conversation_id,
281
+ ],
282
+ outputs=chatbot,
283
+ queue=True,
284
+ )
285
+ stop.click(
286
+ fn=None,
287
+ inputs=None,
288
+ outputs=None,
289
+ cancels=[submit_event, submit_click_event],
290
+ queue=False,
291
+ )
292
+ clear.click(lambda: None, None, chatbot, queue=False)
293
+
294
+ demo.queue(max_size=128, concurrency_count=2)
295
+
296
+ # Launch your Guanaco Demo!
297
+ demo.launch()
298
+
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ bitsandbytes
2
+ transformers
3
+ peft
4
+ accelerate
5
+ gradio
6
+ sentencepiece