nuojohnchen commited on
Commit
21dc656
Β·
verified Β·
1 Parent(s): 0efa248

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -50
app.py CHANGED
@@ -1,64 +1,152 @@
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("nuojohnchen/codellama-7b-sft-v1.3")
8
 
9
- @spaces.GPU(duration=120)
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
  import gradio as gr
2
+ import os
3
+ import spaces
4
+ from transformers import GemmaTokenizer, AutoModelForCausalLM
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
+ from threading import Thread
7
 
8
+ # Set an environment variable
9
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
10
+
11
+
12
+ DESCRIPTION = '''
13
+ <div>
14
+ <h1 style="text-align: center;">Meta Llama3 8B</h1>
15
+ <p>This Space demonstrates the instruction-tuned model <a href="https://huggingface.co/FreedomIntelligence/Apollo-7B"><b>Meta Llama3 8b Chat</b></a>. Meta Llama3 is the new open LLM and comes in two sizes: 8b and 70b. Feel free to play with it, or duplicate to run privately!</p>
16
+ <p>πŸ”Ž For more details about the Llama3 release and how to use the model with <code>transformers</code>, take a look <a href="https://huggingface.co/blog/llama3">at our blog post</a>.</p>
17
+ <p>πŸ¦• Looking for an even more powerful model? Check out the <a href="https://huggingface.co/chat/"><b>Hugging Chat</b></a> integration for Meta Llama 3 70b</p>
18
+ </div>
19
+ '''
20
+
21
+ LICENSE = """
22
+ <p/>
23
+ ---
24
+ Built with Meta Llama 3
25
  """
 
 
 
26
 
27
+ PLACEHOLDER = """
28
+ <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
29
+ <img src="https://ysharma-dummy-chat-app.hf.space/file=/tmp/gradio/8e75e61cc9bab22b7ce3dec85ab0e6db1da5d107/Meta_lockup_positive%20primary_RGB.jpg" style="width: 80%; max-width: 550px; height: auto; opacity: 0.55; ">
30
+ <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">Meta llama3</h1>
31
+ <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything...</p>
32
+ </div>
33
+ """
 
 
 
34
 
 
 
 
 
 
35
 
36
+ css = """
37
+ h1 {
38
+ text-align: center;
39
+ display: block;
40
+ }
41
+ #duplicate-button {
42
+ margin: auto;
43
+ color: white;
44
+ background: #1565c0;
45
+ border-radius: 100vh;
46
+ }
47
+ """
48
 
49
+ # Load the tokenizer and model
50
+ tokenizer = AutoTokenizer.from_pretrained("nuojohnchen/codellama-7b-sft-v1.3")
51
 
52
+ model = AutoModelForCausalLM.from_pretrained("nuojohnchen/codellama-7b-sft-v1.3", device_map="auto") # to("cuda:0")
53
+ terminators = [
54
+ tokenizer.eos_token_id,
55
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
56
+ ]
 
 
 
57
 
58
+ @spaces.GPU(duration=120)
59
+ def chat_llama3_8b(message: str,
60
+ history: list,
61
+ temperature: float,
62
+ max_new_tokens: int
63
+ ) -> str:
64
+ """
65
+ Generate a streaming response using the llama3-8b model.
66
+ Args:
67
+ message (str): The input message.
68
+ history (list): The conversation history used by ChatInterface.
69
+ temperature (float): The temperature for generating the response.
70
+ max_new_tokens (int): The maximum number of new tokens to generate.
71
+ Returns:
72
+ str: The generated response.
73
+ """
74
+ # Build conversation as pure array format
75
+ history_messages = []
76
+ for user, assistant in history:
77
+ history_messages.extend(assistant)
78
+
79
+ # conversation = [
80
+ # message, # ε½“ε‰ζΆˆζ―
81
+ # history_messages # εŽ†ε²ζΆˆζ―ζ•°η»„
82
+ # ]
83
+ conversation = ""
84
+ for user, assistant in history:
85
+ conversation += f"User: {user}\nAssistant: {assistant}<|endoftext|>\n"
86
+ conversation += f"User: {message}\nAssistant: "
87
+
88
+ tokenizer.chat_template = "User:{query}\nAssistant:{response}<|endoftext|>"
89
+ input_ids = tokenizer.encode(conversation, return_tensors="pt").to(model.device)
90
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
91
 
92
+ generate_kwargs = dict(
93
+ input_ids= input_ids,
94
+ streamer=streamer,
95
+ max_new_tokens=max_new_tokens,
96
+ do_sample=True,
97
+ temperature=temperature,
98
+ eos_token_id=terminators,
99
+ )
100
+ # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
101
+ if temperature == 0:
102
+ generate_kwargs['do_sample'] = False
103
+
104
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
105
+ t.start()
106
 
107
+ outputs = []
108
+ for text in streamer:
109
+ outputs.append(text)
110
+ #print(outputs)
111
+ yield "".join(outputs)
112
+
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
+ # Gradio block
115
+ chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
116
 
117
+ with gr.Blocks(fill_height=True, css=css) as demo:
118
+
119
+ gr.Markdown(DESCRIPTION)
120
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
121
+ gr.ChatInterface(
122
+ fn=chat_llama3_8b,
123
+ chatbot=chatbot,
124
+ fill_height=True,
125
+ additional_inputs_accordion=gr.Accordion(label="βš™οΈ Parameters", open=False, render=False),
126
+ additional_inputs=[
127
+ gr.Slider(minimum=0,
128
+ maximum=1,
129
+ step=0.1,
130
+ value=0.95,
131
+ label="Temperature",
132
+ render=False),
133
+ gr.Slider(minimum=128,
134
+ maximum=4096,
135
+ step=1,
136
+ value=512,
137
+ label="Max new tokens",
138
+ render=False ),
139
+ ],
140
+ examples=[
141
+ ['How to setup a human base on Mars? Give short answer.'],
142
+ ['What is 9,000 * 9,000?'],
143
+ ['Write a pun-filled happy birthday message to my friend Alex.'],
144
+ ['Justify why a penguin might make a good king of the jungle.']
145
+ ],
146
+ cache_examples=False,
147
+ )
148
+
149
+ gr.Markdown(LICENSE)
150
+
151
  if __name__ == "__main__":
152
+ demo.launch()