StevenChen16 commited on
Commit
7506bcb
1 Parent(s): 787059d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -30
app.py CHANGED
@@ -1,31 +1,38 @@
1
  import gradio as gr
2
  import os
 
 
3
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
4
  from threading import Thread
5
 
6
  # Set an environment variable
7
  HF_TOKEN = os.environ.get("HF_TOKEN", None)
8
 
 
9
  DESCRIPTION = '''
10
  <div>
11
- <h1 style="text-align: center;">AI Lawyer</h1>
12
- <p>This Space demonstrates the instruction-tuned model <a href="https://huggingface.co/StevenChen16/llama3-8b-Lawyer"><b>StevenChen16/llama3-8b-Lawyer</b></a>. This model is fine-tuned to provide legal information and assist with a wide range of legal questions. Feel free to ask anything!</p>
 
 
13
  </div>
14
  '''
15
 
16
  LICENSE = """
17
  <p/>
18
  ---
19
- Built with model "StevenChen16/Llama3-8B-Lawyer", based on "meta-llama/Meta-Llama-3-8B"
20
  """
21
 
22
  PLACEHOLDER = """
23
  <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
24
- <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">AI Lawyer</h1>
25
- <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything about US and Canada law...</p>
 
26
  </div>
27
  """
28
 
 
29
  css = """
30
  h1 {
31
  text-align: center;
@@ -41,13 +48,28 @@ h1 {
41
 
42
  # Load the tokenizer and model
43
  tokenizer = AutoTokenizer.from_pretrained("StevenChen16/llama3-8b-Lawyer")
44
- model = AutoModelForCausalLM.from_pretrained("StevenChen16/llama3-8b-Lawyer", device_map="auto")
45
  terminators = [
46
  tokenizer.eos_token_id,
47
- tokenizer.convert_tokens_to_ids("")
48
  ]
49
 
50
- def chat_llama3_8b(message: str, history: list, temperature: float, max_new_tokens: int):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  conversation = []
52
  for user, assistant in history:
53
  conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
@@ -58,13 +80,14 @@ def chat_llama3_8b(message: str, history: list, temperature: float, max_new_toke
58
  streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
59
 
60
  generate_kwargs = dict(
61
- input_ids=input_ids,
62
  streamer=streamer,
63
  max_new_tokens=max_new_tokens,
64
  do_sample=True,
65
  temperature=temperature,
66
  eos_token_id=terminators,
67
  )
 
68
  if temperature == 0:
69
  generate_kwargs['do_sample'] = False
70
 
@@ -74,33 +97,36 @@ def chat_llama3_8b(message: str, history: list, temperature: float, max_new_toke
74
  outputs = []
75
  for text in streamer:
76
  outputs.append(text)
 
77
  yield "".join(outputs)
 
78
 
79
  # Gradio block
80
- chatbot = gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
81
 
82
- with gr.Blocks(css=css) as demo:
 
83
  gr.Markdown(DESCRIPTION)
84
- gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
85
  gr.ChatInterface(
86
  fn=chat_llama3_8b,
87
  chatbot=chatbot,
88
  fill_height=True,
89
- additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
90
- additional_inputs=[
91
- gr.Slider(minimum=0,
92
- maximum=1,
93
- step=0.1,
94
- value=0.95,
95
- label="Temperature",
96
- render=False),
97
- gr.Slider(minimum=128,
98
- maximum=4096,
99
- step=1,
100
- value=512,
101
- label="Max new tokens",
102
- render=False ),
103
- ],
104
  examples=[
105
  ['What are the key differences between a sole proprietorship and a partnership?'],
106
  ['What legal steps should I take if I want to start a business in the US?'],
@@ -109,8 +135,9 @@ with gr.Blocks(css=css) as demo:
109
  ['How can I protect my intellectual property when sharing my idea with potential investors?']
110
  ],
111
  cache_examples=False,
112
- )
 
113
  gr.Markdown(LICENSE)
114
-
115
  if __name__ == "__main__":
116
- demo.launch(share=True)
 
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/StevenChen16/llama3-8b-Lawyer"><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;
 
48
 
49
  # Load the tokenizer and model
50
  tokenizer = AutoTokenizer.from_pretrained("StevenChen16/llama3-8b-Lawyer")
51
+ model = AutoModelForCausalLM.from_pretrained("StevenChen16/llama3-8b-Lawyer", 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}])
 
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
 
 
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
  ['What are the key differences between a sole proprietorship and a partnership?'],
132
  ['What legal steps should I take if I want to start a business in the US?'],
 
135
  ['How can I protect my intellectual property when sharing my idea with potential investors?']
136
  ],
137
  cache_examples=False,
138
+ )
139
+
140
  gr.Markdown(LICENSE)
141
+
142
  if __name__ == "__main__":
143
+ demo.launch()