ysharma HF Staff commited on
Commit
7cc686b
·
1 Parent(s): 47a7e1a

create app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -0
app.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer
4
+ import time
5
+ import numpy as np
6
+ from torch.nn import functional as F
7
+ import os
8
+ from threading import Thread
9
+
10
+ # init
11
+ tok = AutoTokenizer.from_pretrained("togethercomputer/RedPajama-INCITE-Chat-3B-v1")
12
+ m = AutoModelForCausalLM.from_pretrained("togethercomputer/RedPajama-INCITE-Chat-3B-v1", torch_dtype=torch.float16)
13
+ m = model.to('cuda:0')
14
+
15
+ class StopOnTokens(StoppingCriteria):
16
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
17
+ #stop_ids = [[29, 13961, 31], [29, 12042, 31], 1, 0]
18
+ stop_ids = [29, 0]
19
+ for stop_id in stop_ids:
20
+ #print(f"^^input ids - {input_ids}")
21
+ if input_ids[0][-1] == stop_id:
22
+ return True
23
+ return False
24
+
25
+
26
+ def user(message, history):
27
+ # Append the user's message to the conversation history
28
+ return "", history + [[message, ""]]
29
+
30
+
31
+
32
+ def chat(curr_system_message, history):
33
+ # Initialize a StopOnTokens object
34
+ stop = StopOnTokens()
35
+
36
+ # Construct the input message string for the model by concatenating the current system message and conversation history
37
+ messages = "".join(["".join(["\n<human>:"+item[0], "\n<bot>:"+item[1]]) #curr_system_message +
38
+ for item in history])
39
+
40
+ # Tokenize the messages string
41
+ model_inputs = tok([messages], return_tensors="pt").to("cuda")
42
+ streamer = TextIteratorStreamer(
43
+ tok, timeout=10., skip_prompt=False, skip_special_tokens=True)
44
+ generate_kwargs = dict(
45
+ model_inputs,
46
+ streamer=streamer,
47
+ max_new_tokens=1024,
48
+ do_sample=True,
49
+ top_p=0.95,
50
+ top_k=1000,
51
+ temperature=1.0,
52
+ num_beams=1,
53
+ stopping_criteria=StoppingCriteriaList([stop])
54
+ )
55
+ t = Thread(target=m.generate, kwargs=generate_kwargs)
56
+ t.start()
57
+
58
+ # print(history)
59
+ # Initialize an empty string to store the generated text
60
+ partial_text = ""
61
+ for new_text in streamer:
62
+ print(new_text)
63
+ if new_text != '<':
64
+ partial_text += new_text
65
+ history[-1][1] = partial_text.split('<bot>:')[-1]
66
+ # Yield an empty string to cleanup the message textbox and the updated conversation history
67
+ yield history
68
+ return partial_text
69
+
70
+
71
+ with gr.Blocks() as demo:
72
+ gr.Markdown("## RedPajama-INCITE-Chat-3B-v1")
73
+ gr.HTML('''<center><a href="https://huggingface.co/spaces/ysharma/RedPajama-Chat-3B?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>Duplicate the Space to skip the queue and run in a private space</center>''')
74
+ chatbot = gr.Chatbot().style(height=500)
75
+ with gr.Row():
76
+ with gr.Column():
77
+ msg = gr.Textbox(label="Chat Message Box", placeholder="Chat Message Box",
78
+ show_label=False).style(container=False)
79
+ with gr.Column():
80
+ with gr.Row():
81
+ submit = gr.Button("Submit")
82
+ stop = gr.Button("Stop")
83
+ clear = gr.Button("Clear")
84
+ system_msg = gr.Textbox(
85
+ start_message, label="System Message", interactive=False, visible=False)
86
+
87
+ submit_event = msg.submit(fn=user, inputs=[msg, chatbot], outputs=[msg, chatbot], queue=False).then(
88
+ fn=chat, inputs=[system_msg, chatbot], outputs=[chatbot], queue=True)
89
+ submit_click_event = submit.click(fn=user, inputs=[msg, chatbot], outputs=[msg, chatbot], queue=False).then(
90
+ fn=chat, inputs=[system_msg, chatbot], outputs=[chatbot], queue=True)
91
+ stop.click(fn=None, inputs=None, outputs=None, cancels=[
92
+ submit_event, submit_click_event], queue=False)
93
+ clear.click(lambda: None, None, [chatbot], queue=False)
94
+
95
+ demo.queue(max_size=32, concurrency_count=2)
96
+ demo.launch(debug=True)