chheplo commited on
Commit
b35805b
·
verified ·
1 Parent(s): 5bb07d5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -124
app.py CHANGED
@@ -1,146 +1,122 @@
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
- ---
25
- Built with Meta Llama 3
26
- """
27
-
28
- PLACEHOLDER = """
29
- <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
30
- <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; ">
31
- <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">Meta llama3</h1>
32
- <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything...</p>
33
- </div>
34
- """
35
-
36
-
37
- css = """
38
- h1 {
39
- text-align: center;
40
- display: block;
41
- }
42
 
43
- #duplicate-button {
44
- margin: auto;
45
- color: white;
46
- background: #1565c0;
47
- border-radius: 100vh;
48
- }
49
- """
50
 
51
- # Load the tokenizer and model
52
- tokenizer = AutoTokenizer.from_pretrained("chheplo/sft_8b_2_llama3")
53
- model = AutoModelForCausalLM.from_pretrained("chheplo/sft_8b_2_llama3", device_map="auto") # to("cuda:0")
 
54
  terminators = [
55
- tokenizer.eos_token_id,
56
- tokenizer.convert_tokens_to_ids("<|eot_id|>")
57
  ]
58
 
59
- @spaces.GPU(duration=120)
60
- def chat_llama3_8b(message: str,
61
- history: list,
62
- temperature: float,
63
- max_new_tokens: int
64
- ) -> str:
65
- """
66
- Generate a streaming response using the llama3-8b model.
67
- Args:
68
- message (str): The input message.
69
- history (list): The conversation history used by ChatInterface.
70
- temperature (float): The temperature for generating the response.
71
- max_new_tokens (int): The maximum number of new tokens to generate.
72
- Returns:
73
- str: The generated response.
74
- """
75
- conversation = []
76
- for user, assistant in history:
77
- conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
78
- conversation.append({"role": "user", "content": message})
79
 
80
- input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
81
-
82
- streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  generate_kwargs = dict(
85
- input_ids= input_ids,
86
  streamer=streamer,
87
- max_new_tokens=max_new_tokens,
88
  do_sample=True,
89
  temperature=temperature,
 
 
90
  eos_token_id=terminators,
91
  )
92
- # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
93
  if temperature == 0:
94
  generate_kwargs['do_sample'] = False
95
-
96
  t = Thread(target=model.generate, kwargs=generate_kwargs)
97
  t.start()
98
 
99
- outputs = []
100
- for text in streamer:
101
- outputs.append(text)
102
- #print(outputs)
103
- yield "".join(outputs)
104
-
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
-
111
- gr.Markdown(DESCRIPTION)
112
- gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
113
- gr.ChatInterface(
114
- fn=chat_llama3_8b,
115
- chatbot=chatbot,
116
- fill_height=True,
117
- additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
118
- additional_inputs=[
119
- gr.Slider(minimum=0,
120
- maximum=1,
121
- step=0.1,
122
- value=0.95,
123
- label="Temperature",
124
- render=False),
125
- gr.Slider(minimum=128,
126
- maximum=4096,
127
- step=1,
128
- value=512,
129
- label="Max new tokens",
130
- render=False ),
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
- ['Write a pun-filled happy birthday message to my friend Alex.'],
137
- ['Justify why a penguin might make a good king of the jungle.']
138
- ],
139
- cache_examples=False,
140
- )
141
-
142
- gr.Markdown(LICENSE)
143
-
144
- if __name__ == "__main__":
145
- demo.launch()
146
-
 
1
  import gradio as gr
2
+ import torch
3
+ from transformers import (
4
+ AutoModelForCausalLM,
5
+ AutoTokenizer,
6
+ TextIteratorStreamer,
7
+ BitsAndBytesConfig,
8
+ )
9
  import os
 
 
 
10
  from threading import Thread
11
+ import spaces
12
+ import time
13
 
14
+ token = os.environ["HF_TOKEN"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ quantization_config = BitsAndBytesConfig(
17
+ load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16
18
+ )
 
 
 
 
19
 
20
+ model = AutoModelForCausalLM.from_pretrained(
21
+ "chheplo/sft_8b_2_llama3", quantization_config=quantization_config, token=token
22
+ )
23
+ tok = AutoTokenizer.from_pretrained("chheplo/sft_8b_2_llama3", token=token)
24
  terminators = [
25
+ tok.eos_token_id,
26
+ tok.convert_tokens_to_ids("<|eot_id|>")
27
  ]
28
 
29
+ if torch.cuda.is_available():
30
+ device = torch.device("cuda")
31
+ print(f"Using GPU: {torch.cuda.get_device_name(device)}")
32
+ else:
33
+ device = torch.device("cpu")
34
+ print("Using CPU")
35
+
36
+ # model = model.to(device)
37
+ # Dispatch Errors
 
 
 
 
 
 
 
 
 
 
 
38
 
 
 
 
39
 
40
+ @spaces.GPU()
41
+ def chat(message, history, temperature,do_sample, max_tokens):
42
+ prompt_template = """
43
+ You are a helpful Agricultural assistant for farmers. You are given the following input. Please complete the response briefly.
44
+ ## Question:
45
+ {}
46
+
47
+ ## Response:
48
+ {}"""
49
+ start_time = time.time()
50
+ chat = []
51
+ # for item in history:
52
+ # chat.append({"role": "user", "content": item[0]})
53
+ # if item[1] is not None:
54
+ # chat.append({"role": "assistant", "content": item[1]})
55
+ # chat.append({"role": "user", "content": message})
56
+ # messages = tok.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
57
+
58
+ model_inputs = tok(prompt_template.format(
59
+ message, #input
60
+ "" # response
61
+ ), return_tensors="pt").to(device)
62
+ streamer = TextIteratorStreamer(
63
+ tok, timeout=10.0, skip_prompt=True, skip_special_tokens=True
64
+ )
65
  generate_kwargs = dict(
66
+ model_inputs,
67
  streamer=streamer,
68
+ max_new_tokens=max_tokens,
69
  do_sample=True,
70
  temperature=temperature,
71
+ repetition_penalty=1.2,
72
+ use_cache=False,
73
  eos_token_id=terminators,
74
  )
75
+
76
  if temperature == 0:
77
  generate_kwargs['do_sample'] = False
78
+
79
  t = Thread(target=model.generate, kwargs=generate_kwargs)
80
  t.start()
81
 
82
+ partial_text = ""
83
+ first_token_time = None
84
+ for new_text in streamer:
85
+ if not first_token_time:
86
+ first_token_time = time.time() - start_time
87
+ partial_text += new_text
88
+ yield partial_text
89
+
90
+ total_time = time.time() - start_time
91
+ tokens = len(tok.tokenize(partial_text))
92
+ tokens_per_second = tokens / total_time if total_time > 0 else 0
93
+
94
+ timing_info = f"\n\nTime taken to first token: {first_token_time:.2f} seconds\nTokens per second: {tokens_per_second:.2f}"
95
+ yield partial_text + timing_info
96
+
97
+
98
+ demo = gr.ChatInterface(
99
+ fn=chat,
100
+ examples=[["I'm a farmer from Odisha, how do I take care of whitefly in my cotton crop?"]],
101
+ # multimodal=False,
102
+ additional_inputs_accordion=gr.Accordion(
103
+ label="⚙️ Parameters", open=False, render=False
104
+ ),
105
+ additional_inputs=[
106
+ gr.Slider(
107
+ minimum=0, maximum=1, step=0.1, value=0.5, label="Temperature", render=False
108
+ ),
109
+ gr.Checkbox(label="Sampling",value=False),
110
+ gr.Slider(
111
+ minimum=128,
112
+ maximum=4096,
113
+ step=1,
114
+ value=512,
115
+ label="Max new tokens",
116
+ render=False,
117
+ ),
118
+ ],
119
+ stop_btn="Stop Generation",
120
+ title="Chat With LLMs",
121
+ description="Now Running [KissanAI/llama3-8b-dhenu-0.1-sft-16bit](https://huggingface.co/KissanAI/llama3-8b-dhenu-0.1-sft-16bit) in 4bit")
122
+ demo.launch()