khulaifi95 commited on
Commit
0b83d47
·
1 Parent(s): 0ac3eb4

feat: add llama template.

Browse files
Files changed (1) hide show
  1. app.py +125 -45
app.py CHANGED
@@ -1,63 +1,143 @@
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__":
 
1
  import gradio as gr
2
+ import os
3
+ import spaces
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
5
+ from threading import Thread
6
+ from typing import Generator
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;">SPUM Table Extraction</h1>
15
+ <p>This Space demonstrates the instruction-tuned model <a href="https://huggingface.co/khulaifi95/Llama-3.1-8B-Reason-Blend-888k"><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
+ </div>
17
  """
18
+
19
+ PLACEHOLDER = """
20
+ <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
21
+ <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; ">
22
+ <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">Materials GPT</h1>
23
+ <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything...</p>
24
+ </div>
25
+ """
26
+
27
+
28
+ css = """
29
+ h1 {
30
+ text-align: center;
31
+ display: block;
32
+ }
33
+ #duplicate-button {
34
+ margin: auto;
35
+ color: white;
36
+ background: #1565c0;
37
+ border-radius: 100vh;
38
+ }
39
  """
 
40
 
41
+ # Load the tokenizer and model
42
+ model_id = "khulaifi95/Llama-3.1-8B-Reason-Blend-888k"
43
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
44
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
45
+ terminators = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|eot_id|>")]
46
 
 
 
 
 
 
 
 
 
 
47
 
48
+ @spaces.GPU(duration=120)
49
+ def chat_llama3_8b(
50
+ message: str, history: list, temperature: float, max_new_tokens: int
51
+ ) -> Generator[str, None, None]:
52
+ """
53
+ Generate a streaming response using the llama3-8b model.
54
+ Args:
55
+ message (str): The input message.
56
+ history (list): The conversation history used by ChatInterface.
57
+ temperature (float): The temperature for generating the response.
58
+ max_new_tokens (int): The maximum number of new tokens to generate.
59
+ Returns:
60
+ str: The generated response.
61
+ """
62
+ conversation = []
63
+ for user, assistant in history:
64
+ conversation.extend(
65
+ [
66
+ {"role": "user", "content": user},
67
+ {"role": "assistant", "content": assistant},
68
+ ]
69
+ )
70
+ conversation.append({"role": "user", "content": message})
71
 
72
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(
73
+ model.device
74
+ )
75
 
76
+ streamer = TextIteratorStreamer(
77
+ tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True
78
+ )
79
 
80
+ generate_kwargs = dict(
81
+ input_ids=input_ids,
82
+ streamer=streamer,
83
+ max_new_tokens=max_new_tokens,
84
+ do_sample=True,
85
  temperature=temperature,
86
+ eos_token_id=terminators,
87
+ )
88
+ # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
89
+ if temperature == 0:
90
+ generate_kwargs["do_sample"] = False
91
 
92
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
93
+ t.start()
94
 
95
+ outputs = []
96
+ for text in streamer:
97
+ outputs.append(text)
98
+ # print(outputs)
99
+ yield "".join(outputs)
100
 
101
+
102
+ # Gradio block
103
+ chatbot = gr.Chatbot(height=450, placeholder=PLACEHOLDER, label="Gradio ChatInterface")
104
+
105
+ with gr.Blocks(fill_height=True, css=css) as demo:
106
+ gr.Markdown(DESCRIPTION)
107
+ gr.ChatInterface(
108
+ fn=chat_llama3_8b,
109
+ chatbot=chatbot,
110
+ fill_height=True,
111
+ additional_inputs_accordion=gr.Accordion(
112
+ label="⚙️ Parameters", open=False, render=False
 
 
 
113
  ),
114
+ additional_inputs=[
115
+ gr.Slider(
116
+ minimum=0,
117
+ maximum=1,
118
+ step=0.1,
119
+ value=0.95,
120
+ label="Temperature",
121
+ render=False,
122
+ ),
123
+ gr.Slider(
124
+ minimum=128,
125
+ maximum=4096,
126
+ step=1,
127
+ value=512,
128
+ label="Max new tokens",
129
+ render=False,
130
+ ),
131
+ ],
132
+ examples=[
133
+ ["How to setup a human base on Mars? Give short answer."],
134
+ ["Explain theory of relativity to me like I’m 8 years old."],
135
+ ["What is 9,000 * 9,000?"],
136
+ ["The detonative temperature of this polypropylene is 2000°F."],
137
+ ["The preparation method according to claim 1, characterized in that the SO2 accounts for 30 wt% and the Fe2O3 accounts for 70 wt%."],
138
+ ],
139
+ cache_examples=False,
140
+ )
141
 
142
 
143
  if __name__ == "__main__":