alfredplpl commited on
Commit
da90805
·
verified ·
1 Parent(s): fe624c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -48
app.py CHANGED
@@ -1,64 +1,139 @@
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
3
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
27
 
28
- response = ""
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- response += token
40
- yield response
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  if __name__ == "__main__":
64
  demo.launch()
 
 
1
+ # Ref: https://huggingface.co/spaces/ysharma/Chat_with_Meta_llama3_8b
2
+
3
  import gradio as gr
4
+ import os
5
+ import spaces
6
+ import torch
7
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
8
+ from threading import Thread
9
 
10
+ DESCRIPTION = '''
11
+ <div>
12
+ <h1 style="text-align: center;">Sarashina2.2-3B Instruct</h1>
13
+ <p>非公式Sarashina2.2-3B Instructだよ。 <a href="https://huggingface.co/sbintuitions/sarashina2.2-3b-instruct-v0.1"><b>sbintuitions/sarashina2.2-3b-instruct-v0.1</b></a>.</p>
14
+ </div>
15
+ '''
16
+
17
+ LICENSE = """
18
+ <p/>
19
+
20
+ ---
21
+ Built with Sarashina
22
  """
 
 
 
23
 
24
+ PLACEHOLDER = """
25
+ <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
26
+ <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">非公式 Sarashina2.2-3B Instruct Test</h1>
27
+ <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">なんでもきいてね</p>
28
+ </div>
29
+ """
30
 
 
 
 
 
 
 
 
 
 
31
 
32
+ css = """
33
+ h1 {
34
+ text-align: center;
35
+ display: block;
36
+ }
37
 
38
+ #duplicate-button {
39
+ margin: auto;
40
+ color: white;
41
+ background: #1565c0;
42
+ border-radius: 100vh;
43
+ }
44
+ """
45
 
46
+ # Load the tokenizer and model
47
+ tokenizer = AutoTokenizer.from_pretrained("sbintuitions/sarashina2.2-3b-instruct-v0.1", use_fast=False)
48
+ model = AutoModelForCausalLM.from_pretrained("sbintuitions/sarashina2.2-3b-instruct-v0.1", torch_dtype=torch.bfloat16)
49
+ model=model.to("cuda:0")
50
 
51
+ @spaces.GPU()
52
+ def chat_llama3_8b(message: str,
53
+ history: list,
54
+ temperature: float,
55
+ max_new_tokens: int
56
+ ) -> str:
57
+ """
58
+ Generate a streaming response using the llama3-8b model.
59
+ Args:
60
+ message (str): The input message.
61
+ history (list): The conversation history used by ChatInterface.
62
+ temperature (float): The temperature for generating the response.
63
+ max_new_tokens (int): The maximum number of new tokens to generate.
64
+ Returns:
65
+ str: The generated response.
66
+ """
67
+ conversation = []
68
+ for user, assistant in history:
69
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
70
+ conversation.append({"role": "user", "content": message})
71
 
72
+ input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True,return_tensors="pt")
73
+
74
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
75
 
76
+ generate_kwargs = dict(
77
+ input_ids= input_ids.to(model.device),
78
+ streamer=streamer,
79
+ max_new_tokens=max_new_tokens,
80
+ do_sample=True,
81
+ temperature=temperature,
82
+ top_p=0.95,
83
+ repetition_penalty=1.1,
84
+ )
85
+ # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
86
+ if temperature == 0:
87
+ generate_kwargs['do_sample'] = False
88
+
89
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
90
+ t.start()
91
 
92
+ outputs = []
93
+ for text in streamer:
94
+ outputs.append(text)
95
+ print(outputs)
96
+ yield "".join(outputs)
97
+
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
+ # Gradio block
100
+ chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
101
 
102
+ with gr.Blocks(fill_height=True, css=css) as demo:
103
+
104
+ gr.Markdown(DESCRIPTION)
105
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
106
+ gr.ChatInterface(
107
+ fn=chat_llama3_8b,
108
+ chatbot=chatbot,
109
+ fill_height=True,
110
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
111
+ additional_inputs=[
112
+ gr.Slider(minimum=0,
113
+ maximum=1,
114
+ step=0.1,
115
+ value=0.5,
116
+ label="Temperature",
117
+ render=False),
118
+ gr.Slider(minimum=128,
119
+ maximum=4096,
120
+ step=1,
121
+ value=512,
122
+ label="Max new tokens",
123
+ render=False ),
124
+ ],
125
+ examples=[
126
+ ['小学生にもわかるように相対性理論を教えてください。'],
127
+ ['宇宙の起源を知るための方法をステップ・バイ・ステップで教えてください。'],
128
+ ['1から100までの素数を求めるスクリプトをPythonで書いてください。'],
129
+ ['友達の陽葵にあげる誕生日プレゼントを考えてください。ただし、陽葵は中学生で、私は同じクラスの男性であることを考慮してください。'],
130
+ ['ペンギンがジャングルの王様であることを正当化するように説明してください。']
131
+ ],
132
+ cache_examples=False,
133
+ )
134
+
135
+ gr.Markdown(LICENSE)
136
+
137
  if __name__ == "__main__":
138
  demo.launch()
139
+