wangzhang commited on
Commit
0fc60cb
·
1 Parent(s): 7c26e10

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -31
app.py CHANGED
@@ -1,36 +1,143 @@
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
3
 
4
- client = InferenceClient(model="wangzhang/chatSDB-test")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- def inference(message, history):
7
- prompt = f"""### Instruction:
8
 
9
- ### Task:
10
- 根据巨杉数据库SequoiaDB的相关问题进行回答。
11
-
12
- ### Input:
13
- {message}
14
-
15
- ### Response:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  """
17
- partial_message = ""
18
- for token in client.text_generation(prompt=prompt, max_new_tokens=512, stream=True, best_of=1, temperature=0.1,
19
- top_p=0.99, do_sample=True, repetition_penalty=1.2):
20
- if token.startswith("<s>"):
21
- return partial_message
22
- partial_message += token
23
- yield partial_message
24
-
25
- gr.ChatInterface(
26
- inference,
27
- chatbot=gr.Chatbot(height=300, scale=7),
28
- textbox=gr.Textbox(placeholder="你可以问我任何关于SequioaDB的问题!", container=False, scale=7),
29
- description="这是SequioaDB旗下的AI智能大语言模型,训练超过上万条真实数据和7亿参数。",
30
- title="ChatSDB",
31
- examples=["SequoiaDB巨杉数据库是什么?", "SequoiaDB巨杉数据库支持哪些类型的数据库实例?"],
32
- retry_btn="重试",
33
- undo_btn="撤销",
34
- clear_btn="清除",
35
- submit_btn="提问",
36
- ).queue().launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from threading import Thread
2
+ from typing import Iterator
3
+
4
  import gradio as gr
5
+ import spaces
6
+ import torch
7
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
8
 
9
+ MAX_MAX_NEW_TOKENS = 2048
10
+ DEFAULT_MAX_NEW_TOKENS = 1024
11
+ MAX_INPUT_TOKEN_LENGTH = 4096
12
+
13
+ DESCRIPTION = """\
14
+ # ChatSDB
15
+
16
+ 这是SequioaDB旗下的AI智能大语言模型,训练超过上万条真实数据和7亿参数。
17
+ ChatSDB是SequoiaDB旗下的AI智能大语言模型,训练超过上万条真实数据和7亿参数</h3>
18
+ <br><strong>模型🔗: <a>https://huggingface.co/wangzhang/ChatSDB </a></strong>
19
+ <br><strong>Dataset🔗: <a>https://huggingface.co/datasets/wangzhang/sdb </a></strong>
20
+ <br><strong> API Doc🔗: <a>https://zgg3nzdpswxy4a-80.proxy.runpod.net/docs/ <a> </strong>
21
+ """
22
+
23
+ LICENSE = """ """
24
+
25
+ if not torch.cuda.is_available():
26
+ DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"
27
+
28
+
29
+ if torch.cuda.is_available():
30
+ model_id = "wangzhang/ChatSDB-hf"
31
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
32
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
33
+ tokenizer.use_default_system_prompt = False
34
 
 
 
35
 
36
+ @spaces.GPU
37
+ def generate(
38
+ message: str,
39
+ chat_history: list[tuple[str, str]],
40
+ system_prompt: str,
41
+ max_new_tokens: int = 512,
42
+ temperature: float = 0.2,
43
+ top_p: float = 0.9,
44
+ top_k: int = 10,
45
+ repetition_penalty: float = 1.2,
46
+ ) -> Iterator[str]:
47
+ conversation = []
48
+ if system_prompt:
49
+ conversation.append({"role": "system", "content": system_prompt})
50
+ for user, assistant in chat_history:
51
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
52
+ prompt = f"""### Instruction:
53
+ 根据巨杉数据库SequoiaDB的相关问题进行回答。
54
+
55
+ ### Input:
56
+ {message}
57
+
58
+ ### Response:
59
  """
60
+ conversation.append({"role": "user", "content": prompt})
61
+ chat = tokenizer.apply_chat_template(conversation, tokenize=False)
62
+ inputs = tokenizer(chat, return_tensors="pt", truncation=True).input_ids.cuda()
63
+ if len(inputs) > MAX_INPUT_TOKEN_LENGTH:
64
+ inputs = inputs[-MAX_INPUT_TOKEN_LENGTH:]
65
+ gr.Warning("Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
66
+
67
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
68
+ generate_kwargs = dict(
69
+ inputs,
70
+ streamer=streamer,
71
+ max_new_tokens=max_new_tokens,
72
+ do_sample=True,
73
+ top_p=top_p,
74
+ top_k=top_k,
75
+ temperature=temperature,
76
+ num_beams=1,
77
+ repetition_penalty=repetition_penalty,
78
+ )
79
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
80
+ t.start()
81
+
82
+ outputs = []
83
+ for text in streamer:
84
+ outputs.append(text)
85
+ yield "".join(outputs)
86
+
87
+
88
+ chat_interface = gr.ChatInterface(
89
+ fn=generate,
90
+ additional_inputs=[
91
+ gr.Textbox(label="System prompt", lines=6),
92
+ gr.Slider(
93
+ label="Max new tokens",
94
+ minimum=1,
95
+ maximum=MAX_MAX_NEW_TOKENS,
96
+ step=1,
97
+ value=DEFAULT_MAX_NEW_TOKENS,
98
+ ),
99
+ gr.Slider(
100
+ label="Temperature",
101
+ minimum=0.1,
102
+ maximum=4.0,
103
+ step=0.1,
104
+ value=0.6,
105
+ ),
106
+ gr.Slider(
107
+ label="Top-p (nucleus sampling)",
108
+ minimum=0.05,
109
+ maximum=1.0,
110
+ step=0.05,
111
+ value=0.9,
112
+ ),
113
+ gr.Slider(
114
+ label="Top-k",
115
+ minimum=1,
116
+ maximum=1000,
117
+ step=1,
118
+ value=50,
119
+ ),
120
+ gr.Slider(
121
+ label="Repetition penalty",
122
+ minimum=1.0,
123
+ maximum=2.0,
124
+ step=0.05,
125
+ value=1.2,
126
+ ),
127
+ ],
128
+ stop_btn=None,
129
+ examples=[
130
+ ["如何安装巨杉数据库SequioaDB?"],
131
+ ["巨杉数据库SequioaDB有哪些优势?"],
132
+ ["巨杉数据库SequioaDB是什么?"],
133
+ ],
134
+ )
135
+
136
+ with gr.Blocks(css="style.css") as demo:
137
+ gr.Markdown(DESCRIPTION)
138
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
139
+ chat_interface.render()
140
+ gr.Markdown(LICENSE)
141
+
142
+ if __name__ == "__main__":
143
+ demo.queue(max_size=20).launch()