Lam-Hung commited on
Commit
4426b83
1 Parent(s): befedec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -48
app.py CHANGED
@@ -1,63 +1,137 @@
 
 
 
 
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
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
  additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
  gr.Slider(
 
 
 
 
 
 
 
 
52
  minimum=0.1,
 
 
 
 
 
 
 
53
  maximum=1.0,
54
- value=0.95,
55
  step=0.05,
56
- label="Top-p (nucleus sampling)",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  ),
58
  ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  )
60
 
61
 
62
  if __name__ == "__main__":
63
- demo.launch()
 
1
+ import os
2
+ from threading import Thread
3
+ from typing import Iterator
4
+
5
  import gradio as gr
6
+ #import spaces
7
+ import torch
8
+ from transformers import AutoModelForCausalLM, GemmaTokenizerFast, TextIteratorStreamer
9
+
10
+ MAX_MAX_NEW_TOKENS = 2048
11
+ DEFAULT_MAX_NEW_TOKENS = 1024
12
+ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
13
+
14
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
15
+
16
+ model_id = "google/gemma-2-9b-it"
17
+ tokenizer = GemmaTokenizerFast.from_pretrained(model_id)
18
+ model = AutoModelForCausalLM.from_pretrained(
19
+ model_id,
20
+ device_map="auto",
21
+ torch_dtype=torch.bfloat16,
22
+ )
23
+ model.config.sliding_window = 4096
24
+ model.eval()
25
+
26
+
27
+ #@spaces.GPU(duration=90)
28
+ def generate(
29
+ message: str,
30
+ chat_history: list[tuple[str, str]],
31
+ max_new_tokens: int = 1024,
32
+ temperature: float = 0.6,
33
+ top_p: float = 0.9,
34
+ top_k: int = 50,
35
+ repetition_penalty: float = 1.2,
36
+ ) -> Iterator[str]:
37
+ conversation = []
38
+ for user, assistant in chat_history:
39
+ conversation.extend(
40
+ [
41
+ {"role": "user", "content": user},
42
+ {"role": "assistant", "content": assistant},
43
+ ]
44
+ )
45
+ conversation.append({"role": "user", "content": message})
46
+
47
+ input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
48
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
49
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
50
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
51
+ input_ids = input_ids.to(model.device)
52
+
53
+ streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
54
+ generate_kwargs = dict(
55
+ {"input_ids": input_ids},
56
+ streamer=streamer,
57
+ max_new_tokens=max_new_tokens,
58
+ do_sample=True,
59
  top_p=top_p,
60
+ top_k=top_k,
61
+ temperature=temperature,
62
+ num_beams=1,
63
+ repetition_penalty=repetition_penalty,
64
+ )
65
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
66
+ t.start()
67
+
68
+ outputs = []
69
+ for text in streamer:
70
+ outputs.append(text)
71
+ yield "".join(outputs)
72
 
 
 
73
 
74
+ chat_interface = gr.ChatInterface(
75
+ fn=generate,
76
+ chatbot=gr.Chatbot(height=500, label = "日本語アシスタント", show_label=True),
77
+ textbox=gr.Textbox(placeholder="メッセージを入力してください", container=False, scale=7),
 
78
  additional_inputs=[
 
 
 
79
  gr.Slider(
80
+ label="テキスト作成時の最大単語数",
81
+ minimum=1,
82
+ maximum=MAX_MAX_NEW_TOKENS,
83
+ step=1,
84
+ value=DEFAULT_MAX_NEW_TOKENS,
85
+ ),
86
+ gr.Slider(
87
+ label="創造",
88
  minimum=0.1,
89
+ maximum=4.0,
90
+ step=0.1,
91
+ value=0.2,
92
+ ),
93
+ gr.Slider(
94
+ label="最も確率の高い単語のグループ",
95
+ minimum=0.05,
96
  maximum=1.0,
 
97
  step=0.05,
98
+ value=0.9,
99
+ ),
100
+ gr.Slider(
101
+ label="上位の単語の確率が最も高い(top-k)",
102
+ minimum=1,
103
+ maximum=1000,
104
+ step=1,
105
+ value=50,
106
+ ),
107
+ gr.Slider(
108
+ label="懲罰を繰り返す",
109
+ minimum=1.0,
110
+ maximum=2.0,
111
+ step=0.05,
112
+ value=1.1,
113
  ),
114
  ],
115
+ theme="soft",
116
+ stop_btn=None,
117
+ examples = [
118
+ ["寿司の作り方"],
119
+ ["美しい着物ドレスの選び方"],
120
+ ["地震が起きたらどうするか"],
121
+ ["どうすれば幸せに生きられるか"],
122
+ ["魚を食べることの利点"],
123
+ ["グループで効果的に作業する方法"]
124
+ ],
125
+
126
+ cache_examples=False,
127
+ title = "日本語アシスタント",
128
+ clear_btn="🗑️ 消す",
129
+ undo_btn="↩️ 元に戻す",
130
+ submit_btn="🚀 送信",
131
+ retry_btn="🔄 リトライ",
132
+ additional_inputs_accordion="高度なカスタマイズ",
133
  )
134
 
135
 
136
  if __name__ == "__main__":
137
+ chat_interface.queue(max_size=20).launch()