Spaces:
Build error

akhilsu commited on
Commit
1b7965e
·
verified ·
1 Parent(s): e1d44f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -103
app.py CHANGED
@@ -1,134 +1,119 @@
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
  # Set an environment variable
8
  HF_TOKEN = os.environ.get("HF_TOKEN", None)
9
 
10
- DESCRIPTION = '''
11
- <div style="background-color: #ffffff; padding: 20px; border-radius: 8px; box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);">
12
- <h1 style="text-align: center; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #333;">Meta Llama3 8B</h1>
13
- <p style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #555; text-align: center;">This Space demonstrates the instruction-tuned model <a href="https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct"><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>
14
- <p style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #555; text-align: center;">🔎 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>
15
- <p style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #555; text-align: center;">🦕 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>
16
- </div>
17
- '''
18
-
19
- LICENSE = """
20
- <p style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #999; text-align: center; padding-top: 20px;">---
21
- Built with Meta Llama 3<br>
22
- Developed by Akhil Sudhakaran
23
- </p>
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/8e75e61cc9bab22b7ce3dec85ab0e6db1da5d107/Meta_lockup_positive%20primary_RGB.jpg" style="width: 80%; max-width: 550px; height: auto; opacity: 0.85; border-radius: 8px;">
29
- <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.85; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #444;">Meta Llama3</h1>
30
- <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.75; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #666;">Ask me anything...</p>
31
  </div>
32
  """
33
 
 
34
  css = """
35
- body {
36
- background-color: #f5f5f5;
37
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
38
- }
39
- h1, p {
40
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
41
  }
42
  #duplicate-button {
43
- margin: auto;
44
- color: #ffffff;
45
- background: #007BFF;
46
- border-radius: 100px;
47
- padding: 10px 20px;
48
- border: none;
49
- cursor: pointer;
50
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
51
- transition: background 0.3s ease;
52
- }
53
- #duplicate-button:hover {
54
- background: #0056b3;
55
- }
56
- .gradio-container {
57
- max-width: 850px;
58
- margin: 0 auto;
59
- padding: 20px;
60
- background-color: #ffffff;
61
- border-radius: 8px;
62
- box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);
63
  }
64
  """
65
 
66
  # Load the tokenizer and model
 
 
67
  tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B-Instruct")
68
- model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B-Instruct", device_map="auto")
69
-
70
  terminators = [
71
- tokenizer.eos_token_id,
72
- tokenizer.convert_tokens_to_ids("<|eot_id|>")
73
  ]
74
 
75
  @spaces.GPU(duration=120)
76
- def chat_llama3_8b(message: str, history: list, temperature: float, max_new_tokens: int) -> str:
77
- conversation = []
78
- for user, assistant in history:
79
- conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
80
- conversation.append({"role": "user", "content": message})
81
-
82
- input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
83
-
84
- streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
85
-
86
- generate_kwargs = dict(
87
- input_ids=input_ids,
88
- streamer=streamer,
89
- max_new_tokens=max_new_tokens,
90
- do_sample=True,
91
- temperature=temperature,
92
- eos_token_id=terminators,
93
- )
94
-
95
- if temperature == 0:
96
- generate_kwargs['do_sample'] = False
97
-
98
- t = Thread(target=model.generate, kwargs=generate_kwargs)
99
- t.start()
100
-
101
- outputs = []
102
- for text in streamer:
103
- outputs.append(text)
104
- yield "".join(outputs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
  # Gradio block
107
- chatbot = gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
108
 
109
  with gr.Blocks(fill_height=True, css=css) as demo:
110
- gr.Markdown(DESCRIPTION)
111
- gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
112
- gr.ChatInterface(
113
- fn=chat_llama3_8b,
114
- chatbot=chatbot,
115
- fill_height=True,
116
- additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
117
- additional_inputs=[
118
- gr.Slider(minimum=0, maximum=1, step=0.1, value=0.95, label="Temperature", render=False),
119
- gr.Slider(minimum=128, maximum=4096, step=1, value=512, label="Max new tokens", render=False),
120
- ],
121
- examples=[
122
- ['How to setup a human base on Mars? Give short answer.'],
123
- ['Explain theory of relativity to me like I’m 8 years old.'],
124
- ['What is 9,000 * 9,000?'],
125
- ['Write a pun-filled happy birthday message to my friend Alex.'],
126
- ['Justify why a penguin might make a good king of the jungle.']
127
- ],
128
- cache_examples=False,
129
- )
130
-
131
- gr.Markdown(LICENSE)
132
-
 
133
  if __name__ == "__main__":
134
- 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
  PLACEHOLDER = """
12
  <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
13
+ <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; ">
14
+ <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">Meta llama3</h1>
15
+ <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything...</p>
16
  </div>
17
  """
18
 
19
+
20
  css = """
21
+ h1 {
22
+ text-align: center;
23
+ display: block;
 
 
 
24
  }
25
  #duplicate-button {
26
+ margin: auto;
27
+ color: white;
28
+ background: #1565c0;
29
+ border-radius: 100vh;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  }
31
  """
32
 
33
  # Load the tokenizer and model
34
+ #tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")
35
+ #model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto") # to("cuda:0")
36
  tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B-Instruct")
37
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B-Instruct", device_map="auto") # to("cuda:0")
 
38
  terminators = [
39
+ tokenizer.eos_token_id,
40
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
41
  ]
42
 
43
  @spaces.GPU(duration=120)
44
+ def chat_llama3_8b(message: str,
45
+ history: list,
46
+ temperature: float,
47
+ max_new_tokens: int
48
+ ) -> str:
49
+ """
50
+ Generate a streaming response using the llama3-8b model.
51
+ Args:
52
+ message (str): The input message.
53
+ history (list): The conversation history used by ChatInterface.
54
+ temperature (float): The temperature for generating the response.
55
+ max_new_tokens (int): The maximum number of new tokens to generate.
56
+ Returns:
57
+ str: The generated response.
58
+ """
59
+ conversation = []
60
+ for user, assistant in history:
61
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
62
+ conversation.append({"role": "user", "content": message})
63
+
64
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
65
+
66
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
67
+
68
+ generate_kwargs = dict(
69
+ input_ids= input_ids,
70
+ streamer=streamer,
71
+ max_new_tokens=max_new_tokens,
72
+ do_sample=True,
73
+ temperature=temperature,
74
+ eos_token_id=terminators,
75
+ )
76
+ # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
77
+ if temperature == 0:
78
+ generate_kwargs['do_sample'] = False
79
+
80
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
81
+ t.start()
82
+
83
+ outputs = []
84
+ for text in streamer:
85
+ outputs.append(text)
86
+ #print(outputs)
87
+ yield "".join(outputs)
88
+
89
 
90
  # Gradio block
91
+ chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
92
 
93
  with gr.Blocks(fill_height=True, css=css) as demo:
94
+
95
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
96
+ gr.ChatInterface(
97
+ fn=chat_llama3_8b,
98
+ chatbot=chatbot,
99
+ fill_height=True,
100
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
101
+ additional_inputs=[
102
+ gr.Slider(minimum=0,
103
+ maximum=1,
104
+ step=0.1,
105
+ value=0.95,
106
+ label="Temperature",
107
+ render=False),
108
+ gr.Slider(minimum=128,
109
+ maximum=4096,
110
+ step=1,
111
+ value=512,
112
+ label="Max new tokens",
113
+ render=False ),
114
+ ],
115
+ cache_examples=False,
116
+ )
117
+
118
  if __name__ == "__main__":
119
+ demo.launch()