abhillubillu commited on
Commit
312e99a
Β·
verified Β·
1 Parent(s): 54b9773

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -46
app.py CHANGED
@@ -1,63 +1,157 @@
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("abhillubillu/gameapp_model")
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 gradio as gr
2
+ import os
3
+ import spaces
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
5
+ from threading import Thread
6
 
7
+
8
+ TITLE = '''
9
+ <h1 style="text-align: center;">Meta Llama3.1 8B <a href="https://huggingface.co/spaces/ysharma/Chat_with_Meta_llama3_1_8b?duplicate=true" id="duplicate-button"><button style="color:white">Duplicate this Space</button></a></h1>
10
+ '''
11
+
12
+ DESCRIPTION = '''
13
+ <div>
14
+ <p>This Space demonstrates the instruction-tuned model <a href="https://huggingface.co/meta-llama/Meta-Llama-3.1-8B-Instruct"><b>Meta Llama3.1 8b Chat</b></a>. Feel free to play with this demo, or duplicate to run privately!</p>
15
+ <p>πŸ”¨ Interested in trying out more powerful Instruct versions of Llama3.1? Check out the <a href="https://huggingface.co/chat/"><b>Hugging Chat</b></a> integration for 🐘 Meta Llama 3.1 70b, and πŸ¦• Meta Llama 3.1 405b</p>
16
+ <p>πŸ”Ž For more details about the Llama3.1 release and how to use the model with <code>transformers</code>, take a look <a href="https://huggingface.co/blog/llama31">at our blog post</a>.</p>
17
+ </div>
18
+ '''
19
+
20
+ LICENSE = """
21
+ <p/>
22
+ ---
23
+ Built with Llama
24
+ """
25
+
26
+ PLACEHOLDER = """
27
+ <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
28
+ <img src="https://ysharma-dummy-chat-app.hf.space/file=/tmp/gradio/c21ff9c8e7ecb2f7d957a72f2ef03c610ac7bbc4/Meta_lockup_positive%20primary_RGB_small.jpg" style="width: 80%; max-width: 550px; height: auto; opacity: 0.55; ">
29
+ <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">Meta llama3.1</h1>
30
+ <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything...</p>
31
+ </div>
32
  """
33
+
34
+ css = """
35
+ h1 {
36
+ text-align: center;
37
+ display: block;
38
+ display: flex;
39
+ align-items: center;
40
+ justify-content: center;
41
+ }
42
+
43
+ #duplicate-button {
44
+ margin-left: 10px;
45
+ color: white;
46
+ background: #1565c0;
47
+ border-radius: 100vh;
48
+ font-size: 1rem;
49
+ padding: 3px 5px;
50
+ }
51
  """
 
52
 
53
+ model_id = "meta-llama/Meta-Llama-3.1-8B-Instruct"
54
 
55
+ # Load the tokenizer and model
56
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
57
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
58
+ terminators = [
59
+ tokenizer.eos_token_id,
60
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
61
+ ]
 
 
62
 
63
+ MAX_INPUT_TOKEN_LENGTH = 4096
 
 
 
 
64
 
65
+ # Gradio inference function
66
+ @spaces.GPU(duration=120)
67
+ def chat_llama3_1_8b(message: str,
68
+ history: list,
69
+ temperature: float,
70
+ max_new_tokens: int
71
+ ) -> str:
72
+ """
73
+ Generate a streaming response using the llama3-8b model.
74
+ Args:
75
+ message (str): The input message.
76
+ history (list): The conversation history used by ChatInterface.
77
+ temperature (float): The temperature for generating the response.
78
+ max_new_tokens (int): The maximum number of new tokens to generate.
79
+ Returns:
80
+ str: The generated response.
81
+ """
82
+ conversation = []
83
+ for user, assistant in history:
84
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
85
+ conversation.append({"role": "user", "content": message})
86
 
87
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
88
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
89
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
90
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
91
+ input_ids = input_ids.to(model.device)
92
+
93
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
94
 
95
+ generate_kwargs = dict(
96
+ input_ids= input_ids,
97
+ streamer=streamer,
98
+ max_new_tokens=max_new_tokens,
99
+ do_sample=temperature != 0, # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
100
  temperature=temperature,
101
+ eos_token_id=terminators,
102
+ )
 
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
+ yield "".join(outputs)
111
+
112
+
113
+ # Gradio block
114
+ chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
 
 
 
 
 
 
 
 
 
 
115
 
116
+ with gr.Blocks(fill_height=True, css=css) as demo:
117
 
118
+ gr.Markdown(TITLE)
119
+ gr.Markdown(DESCRIPTION)
120
+ #gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
121
+ gr.ChatInterface(
122
+ fn=chat_llama3_1_8b,
123
+ chatbot=chatbot,
124
+ fill_height=True,
125
+ examples_per_page=3,
126
+ additional_inputs_accordion=gr.Accordion(label="βš™οΈ Parameters", open=False, render=False),
127
+ additional_inputs=[
128
+ gr.Slider(minimum=0,
129
+ maximum=1,
130
+ step=0.1,
131
+ value=0.95,
132
+ label="Temperature",
133
+ render=False),
134
+ gr.Slider(minimum=128,
135
+ maximum=4096,
136
+ step=1,
137
+ value=512,
138
+ label="Max new tokens",
139
+ render=False ),
140
+ ],
141
+ examples=[
142
+ ["There's a llama in my garden 😱 What should I do?"],
143
+ ["What is the best way to open a can of worms?"],
144
+ ["The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1. "],
145
+ ['How to setup a human base on Mars? Give short answer.'],
146
+ ['Explain theory of relativity to me like I’m 8 years old.'],
147
+ ['What is 9,000 * 9,000?'],
148
+ ['Write a pun-filled happy birthday message to my friend Alex.'],
149
+ ['Justify why a penguin might make a good king of the jungle.']
150
+ ],
151
+ cache_examples=False,
152
+ )
153
+
154
+ gr.Markdown(LICENSE)
155
+
156
  if __name__ == "__main__":
157
  demo.launch()