arjunanand13 commited on
Commit
5c01458
·
verified ·
1 Parent(s): bec4bc8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -92
app.py CHANGED
@@ -1,124 +1,143 @@
1
- import os
2
- from threading import Thread
3
- from typing import Iterator
4
-
5
  import gradio as gr
 
6
  import spaces
7
- import torch
8
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
 
9
 
10
- MAX_MAX_NEW_TOKENS = 2048
11
- DEFAULT_MAX_NEW_TOKENS = 1024
12
- MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
13
-
14
  HF_TOKEN = os.environ.get("HF_TOKEN", None)
15
 
16
- model_id = "meta-llama/Llama-2-7b-chat-hf"
17
- model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
18
- tokenizer = AutoTokenizer.from_pretrained(model_id)
19
- tokenizer.use_default_system_prompt = False
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- # @spaces.GPU
23
- def generate(
24
- message: str,
25
- chat_history: list[tuple[str, str]],
26
- system_prompt: str,
27
- max_new_tokens: int = 1024,
28
- temperature: float = 0.6,
29
- top_p: float = 0.9,
30
- top_k: int = 50,
31
- repetition_penalty: float = 1.2,
32
- ) -> Iterator[str]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  conversation = []
34
- if system_prompt:
35
- conversation.append({"role": "system", "content": system_prompt})
36
- for user, assistant in chat_history:
37
  conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
38
  conversation.append({"role": "user", "content": message})
39
 
40
- input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
41
- if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
42
- input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
43
- gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
44
- input_ids = input_ids.to(model.device)
45
-
46
  streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
 
47
  generate_kwargs = dict(
48
- {"input_ids": input_ids},
49
  streamer=streamer,
50
  max_new_tokens=max_new_tokens,
51
  do_sample=True,
52
- top_p=top_p,
53
- top_k=top_k,
54
  temperature=temperature,
55
- num_beams=1,
56
- repetition_penalty=repetition_penalty,
57
  )
 
 
 
 
58
  t = Thread(target=model.generate, kwargs=generate_kwargs)
59
  t.start()
60
 
61
  outputs = []
62
  for text in streamer:
63
  outputs.append(text)
 
64
  yield "".join(outputs)
 
65
 
 
 
66
 
67
- chat_interface = gr.ChatInterface(
68
- fn=generate,
69
- additional_inputs=[
70
- gr.Textbox(label="System prompt", lines=6),
71
- gr.Slider(
72
- label="Max new tokens",
73
- minimum=1,
74
- maximum=MAX_MAX_NEW_TOKENS,
75
- step=1,
76
- value=DEFAULT_MAX_NEW_TOKENS,
77
- ),
78
- gr.Slider(
79
- label="Temperature",
80
- minimum=0.1,
81
- maximum=4.0,
82
- step=0.1,
83
- value=0.6,
84
- ),
85
- gr.Slider(
86
- label="Top-p (nucleus sampling)",
87
- minimum=0.05,
88
- maximum=1.0,
89
- step=0.05,
90
- value=0.9,
91
- ),
92
- gr.Slider(
93
- label="Top-k",
94
- minimum=1,
95
- maximum=1000,
96
- step=1,
97
- value=50,
98
- ),
99
- gr.Slider(
100
- label="Repetition penalty",
101
- minimum=1.0,
102
- maximum=2.0,
103
- step=0.05,
104
- value=1.2,
105
- ),
106
- ],
107
- stop_btn=None,
108
- examples=[
109
- ["Hello there! How are you doing?"],
110
- ["Can you explain briefly to me what is the Python programming language?"],
111
- ["Explain the plot of Cinderella in a sentence."],
112
- ["How many hours does it take a man to eat a Helicopter?"],
113
- ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
114
- ],
115
- )
116
-
117
- with gr.Blocks(css="style.css") as demo:
118
  gr.Markdown(DESCRIPTION)
119
  gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
120
- chat_interface.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  gr.Markdown(LICENSE)
122
-
123
  if __name__ == "__main__":
124
- demo.queue(max_size=20).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/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>
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("meta-llama/Meta-Llama-3-8B-Instruct")
51
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto") # to("cuda:0")
52
+ terminators = [
53
+ tokenizer.eos_token_id,
54
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
55
+ ]
56
+
57
+ @spaces.GPU(duration=120)
58
+ def chat_llama3_8b(message: str,
59
+ history: list,
60
+ temperature: float,
61
+ max_new_tokens: int
62
+ ) -> str:
63
+ """
64
+ Generate a streaming response using the llama3-8b model.
65
+ Args:
66
+ message (str): The input message.
67
+ history (list): The conversation history used by ChatInterface.
68
+ temperature (float): The temperature for generating the response.
69
+ max_new_tokens (int): The maximum number of new tokens to generate.
70
+ Returns:
71
+ str: The generated response.
72
+ """
73
  conversation = []
74
+ for user, assistant in history:
 
 
75
  conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
76
  conversation.append({"role": "user", "content": message})
77
 
78
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
79
+
 
 
 
 
80
  streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
81
+
82
  generate_kwargs = dict(
83
+ input_ids= input_ids,
84
  streamer=streamer,
85
  max_new_tokens=max_new_tokens,
86
  do_sample=True,
 
 
87
  temperature=temperature,
88
+ eos_token_id=terminators,
 
89
  )
90
+ # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
91
+ if temperature == 0:
92
+ generate_kwargs['do_sample'] = False
93
+
94
  t = Thread(target=model.generate, kwargs=generate_kwargs)
95
  t.start()
96
 
97
  outputs = []
98
  for text in streamer:
99
  outputs.append(text)
100
+ print(outputs)
101
  yield "".join(outputs)
102
+
103
 
104
+ # Gradio block
105
+ chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
106
 
107
+ with gr.Blocks(fill_height=True, css=css) as demo:
108
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  gr.Markdown(DESCRIPTION)
110
  gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
111
+ gr.ChatInterface(
112
+ fn=chat_llama3_8b,
113
+ chatbot=chatbot,
114
+ fill_height=True,
115
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
116
+ additional_inputs=[
117
+ gr.Slider(minimum=0,
118
+ maximum=1,
119
+ step=0.1,
120
+ value=0.95,
121
+ label="Temperature",
122
+ render=False),
123
+ gr.Slider(minimum=128,
124
+ maximum=4096,
125
+ step=1,
126
+ value=512,
127
+ label="Max new tokens",
128
+ render=False ),
129
+ ],
130
+ examples=[
131
+ ['How to setup a human base on Mars? Give short answer.'],
132
+ ['Explain theory of relativity to me like I’m 8 years old.'],
133
+ ['What is 9,000 * 9,000?'],
134
+ ['Write a pun-filled happy birthday message to my friend Alex.'],
135
+ ['Justify why a penguin might make a good king of the jungle.']
136
+ ],
137
+ cache_examples=False,
138
+ )
139
+
140
  gr.Markdown(LICENSE)
141
+
142
  if __name__ == "__main__":
143
+ demo.launch()