Chetan Khadke commited on
Commit
4dc99bb
β€’
1 Parent(s): 06506e0

changes added

Browse files
Files changed (2) hide show
  1. app.py +108 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ print(f"Starting to load the model to memory")
11
+ #m = AutoModelForCausalLM.from_pretrained(
12
+ # "stabilityai/stablelm-tuned-alpha-3b", torch_dtype=torch.float16).cuda()
13
+ #tok = AutoTokenizer.from_pretrained("stabilityai/stablelm-tuned-alpha-7b")
14
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
15
+
16
+ quantization_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True)
17
+ tok = AutoTokenizer.from_pretrained("stabilityai/stablelm-tuned-alpha-3b", device_map="auto", load_in_8bit=True, torch_dtype=torch.float16 )
18
+ m = AutoModelForCausalLM.from_pretrained("stabilityai/stablelm-tuned-alpha-3b", device_map= "auto", quantization_config=quantization_config)
19
+ generator = pipeline('text-generation', model=m, tokenizer=tok, device=0)
20
+ print(f"Sucessfully loaded the model to the memory")
21
+
22
+ start_message = """<|SYSTEM|># StableAssistant
23
+ - StableAssistant is A helpful and harmless Open Source AI Language Model developed by Stability and CarperAI.
24
+ - StableAssistant is excited to be able to help the user, but will refuse to do anything that could be considered harmful to the user.
25
+ - StableAssistant is more than just an information source, StableAssistant is also able to write poetry, short stories, and make jokes.
26
+ - StableAssistant will refuse to participate in anything that could harm a human."""
27
+
28
+
29
+ class StopOnTokens(StoppingCriteria):
30
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
31
+ stop_ids = [50278, 50279, 50277, 1, 0]
32
+ for stop_id in stop_ids:
33
+ if input_ids[0][-1] == stop_id:
34
+ return True
35
+ return False
36
+
37
+
38
+ def user(message, history):
39
+ # Append the user's message to the conversation history
40
+ return "", history + [[message, ""]]
41
+
42
+
43
+ def chat(curr_system_message, history):
44
+ # Initialize a StopOnTokens object
45
+ stop = StopOnTokens()
46
+
47
+ # Construct the input message string for the model by concatenating the current system message and conversation history
48
+ messages = curr_system_message + \
49
+ "".join(["".join(["<|USER|>"+item[0], "<|ASSISTANT|>"+item[1]])
50
+ for item in history])
51
+
52
+ # Tokenize the messages string
53
+ model_inputs = tok([messages], return_tensors="pt").to("cuda")
54
+ streamer = TextIteratorStreamer(
55
+ tok, timeout=10., skip_prompt=True, skip_special_tokens=True)
56
+ generate_kwargs = dict(
57
+ model_inputs,
58
+ streamer=streamer,
59
+ max_new_tokens=1024,
60
+ do_sample=True,
61
+ top_p=0.95,
62
+ top_k=1000,
63
+ temperature=1.0,
64
+ num_beams=1,
65
+ stopping_criteria=StoppingCriteriaList([stop])
66
+ )
67
+ t = Thread(target=m.generate, kwargs=generate_kwargs)
68
+ t.start()
69
+
70
+ # print(history)
71
+ # Initialize an empty string to store the generated text
72
+ partial_text = ""
73
+ for new_text in streamer:
74
+ # print(new_text)
75
+ partial_text += new_text
76
+ history[-1][1] = partial_text
77
+ # Yield an empty string to cleanup the message textbox and the updated conversation history
78
+ yield history
79
+ return partial_text
80
+
81
+
82
+ with gr.Blocks() as demo:
83
+ # history = gr.State([])
84
+ gr.Markdown("## StableLM-Tuned-Alpha-7b Chat")
85
+ gr.HTML('''<center><a href="https://huggingface.co/spaces/stabilityai/stablelm-tuned-alpha-chat?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>''')
86
+ chatbot = gr.Chatbot().style(height=500)
87
+ with gr.Row():
88
+ with gr.Column():
89
+ msg = gr.Textbox(label="Chat Message Box", placeholder="Chat Message Box",
90
+ show_label=False).style(container=False)
91
+ with gr.Column():
92
+ with gr.Row():
93
+ submit = gr.Button("Submit")
94
+ stop = gr.Button("Stop")
95
+ clear = gr.Button("Clear")
96
+ system_msg = gr.Textbox(
97
+ start_message, label="System Message", interactive=False, visible=False)
98
+
99
+ submit_event = msg.submit(fn=user, inputs=[msg, chatbot], outputs=[msg, chatbot], queue=False).then(
100
+ fn=chat, inputs=[system_msg, chatbot], outputs=[chatbot], queue=True)
101
+ submit_click_event = submit.click(fn=user, inputs=[msg, chatbot], outputs=[msg, chatbot], queue=False).then(
102
+ fn=chat, inputs=[system_msg, chatbot], outputs=[chatbot], queue=True)
103
+ stop.click(fn=None, inputs=None, outputs=None, cancels=[
104
+ submit_event, submit_click_event], queue=False)
105
+ clear.click(lambda: None, None, [chatbot], queue=False)
106
+
107
+ demo.queue(max_size=32, concurrency_count=2)
108
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio
2
+ torch
3
+ transformers
4
+ numpy
5
+ bitsandbytes
6
+ accelerate