mitsu-koh commited on
Commit
923d029
1 Parent(s): 61f5283

Update app.py

Browse files
Files changed (3) hide show
  1. README.md +3 -3
  2. app.py +132 -47
  3. requirements.txt +3 -1
README.md CHANGED
@@ -1,8 +1,8 @@
1
  ---
2
- title: Gradio Chatbot
3
- emoji: 💬
4
  colorFrom: yellow
5
- colorTo: purple
6
  sdk: gradio
7
  sdk_version: 4.36.1
8
  app_file: app.py
 
1
  ---
2
+ title: Gemma 2 Baku 2B Instruct
3
+ emoji: 🐼
4
  colorFrom: yellow
5
+ colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 4.36.1
8
  app_file: app.py
app.py CHANGED
@@ -1,63 +1,148 @@
 
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
  import gradio as gr
3
+ import spaces
4
+ from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
5
+ from threading import Thread
6
 
7
+
8
+ # Set an environment variable
9
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
10
+
11
+ model_icon = "🐼"
12
+ model_name = "Gemma 2 Baku 2B Instruct"
13
+ model_url = "https://huggingface.co/rinna/gemma-2-baku-2b-it"
14
+ model_id = "rinna/gemma-2-baku-2b-it"
15
+ base_model_url = "https://huggingface.co/google/gemma-2-2b"
16
+ base_model_name = "Gemma 2 2B"
17
+ press_url = "https://rinna.co.jp/news/2024/07/20240725.html"
18
+ logo_url = "https://huggingface.co/rinna/gemma-2-baku-2b/resolve/main/rinna.png"
19
+
20
+ LICENSE = """
21
+ ---
22
+ <div>
23
+ <p>License: <a href="https://ai.google.dev/gemma/terms">Gemma Terms of Use </a><p>
24
+ <p>This space is implemented based on <a href="https://huggingface.co/spaces/ysharma/Chat_with_Meta_llama3_8b">ysharma/Chat_with_Meta_llama3_8b</a>.</p>
25
+ </div>
26
  """
27
+
28
+
29
+ DESCRIPTION = f"""
30
+ <div>
31
+ <p>{model_icon} <a href="{model_url}"><b>{model_name}</b> ({model_id})</a>は、<a href="https://rinna.co.jp">rinna株式会社</a>が<a href="{base_model_url}">{base_model_name}</a>に日本語継続事前学習およびインストラクションチューニングを行った大規模言語モデルです.{base_model_name}の優れたパフォーマンスを日本語に引き継いでおり、日本語のチャットにおいて高い性能を示しています。</p>
32
+ <p>🤖 このデモでは、{model_name}とチャットを行うことが可能です。</p>
33
+ <p>📄 モデルの詳細については、<a href="{press_url}">プレスリリース</a>、および、<a href="https://rinnakk.github.io/research/benchmarks/lm/index.html">ベンチマーク</a>をご覧ください。お問い合わせは<a href="https://rinna.co.jp/inquiry/">こちら</a>までどうぞ。</p>
34
+ </div>
35
  """
 
36
 
37
+ PLACEHOLDER = f"""
38
+ <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
39
+ <img src="{logo_url}" style="width: 80%; max-width: 550px; height: auto; opacity: 0.55; ">
40
+ <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">{model_name}</h1>
41
+ </div>
42
+ """
43
 
44
+ css = """
45
+ h1 {
46
+ text-align: center;
47
+ display: block;
48
+ }
49
+ #duplicate-button {
50
+ margin: auto;
51
+ color: white;
52
+ background: #1565c0;
53
+ border-radius: 100vh;
54
+ }
55
+ """
56
+
57
+
58
+ # Load the tokenizer and model
59
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
60
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
61
 
 
 
 
 
 
62
 
63
+ @spaces.GPU(duration=120)
64
+ def chat_llama3_8b(message: str,
65
+ history: list,
66
+ temperature: float,
67
+ max_new_tokens: int
68
+ ) -> str:
69
+ """
70
+ Generate a streaming response using the llama3-8b model.
71
+ Args:
72
+ message (str): The input message.
73
+ history (list): The conversation history used by ChatInterface.
74
+ temperature (float): The temperature for generating the response.
75
+ max_new_tokens (int): The maximum number of new tokens to generate.
76
+ Returns:
77
+ str: The generated response.
78
+ """
79
+ conversation = []
80
+ for user, assistant in history:
81
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
82
+ conversation.append({"role": "user", "content": message})
83
 
84
+ # Need to set add_generation_prompt=True to ensure the model generates the response.
85
+ input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt").to(model.device)
86
+
87
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
88
 
89
+ generate_kwargs = dict(
90
+ input_ids=input_ids,
91
+ streamer=streamer,
92
+ max_new_tokens=max_new_tokens,
93
+ do_sample=True,
94
  temperature=temperature,
95
+ repetition_penalty=1.1,
96
+ )
97
+ # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
98
+ if temperature == 0:
99
+ generate_kwargs['do_sample'] = False
100
+
101
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
102
+ t.start()
103
 
104
+ outputs = []
105
+ for text in streamer:
106
+ outputs.append(text)
107
+ yield "".join(outputs)
108
+
109
 
110
+ # Gradio block
111
+ chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
+ with gr.Blocks(fill_height=True, css=css) as demo:
114
+
115
+ gr.Markdown(DESCRIPTION)
116
+ gr.ChatInterface(
117
+ fn=chat_llama3_8b,
118
+ chatbot=chatbot,
119
+ fill_height=True,
120
+ additional_inputs_accordion=gr.Accordion(label="⚙️ パラメータ", open=False, render=False),
121
+ additional_inputs=[
122
+ gr.Slider(minimum=0,
123
+ maximum=1,
124
+ step=0.05,
125
+ value=0.9,
126
+ label="生成時におけるサンプリングの温度(ランダム性)",
127
+ render=False),
128
+ gr.Slider(minimum=128,
129
+ maximum=4096,
130
+ step=1,
131
+ value=512,
132
+ label="生成したい最大のトークン数",
133
+ render=False),
134
+ ],
135
+ examples=[
136
+ ["日本で有名なものと言えば"],
137
+ ["ネコ: 「お腹が減ったニャ」\nから始まる物語を書いて"],
138
+ ["C言語で素数を判定するコードを書いて"],
139
+ ["人工知能とは何ですか"],
140
+ ],
141
+ cache_examples=False,
142
+ )
143
+
144
+ gr.Markdown(LICENSE)
145
+
146
 
147
  if __name__ == "__main__":
148
+ demo.launch()
requirements.txt CHANGED
@@ -1 +1,3 @@
1
- huggingface_hub==0.22.2
 
 
 
1
+ accelerate
2
+ transformers
3
+ SentencePiece