itaudit commited on
Commit
bd4f08e
·
verified ·
1 Parent(s): d446dc4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -158
app.py CHANGED
@@ -1,168 +1,149 @@
1
- import os
2
- import time
3
  import spaces
4
- import torch
5
- from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, BitsAndBytesConfig
 
 
 
 
 
6
  import gradio as gr
7
- from threading import Thread
8
-
9
- MODEL_LIST = ["meta-llama/Meta-Llama-3.1-8B-Instruct"]
10
- HF_TOKEN = os.environ.get("HF_TOKEN", None)
11
- MODEL = os.environ.get("MODEL_ID")
12
-
13
- TITLE = "<h1><center>Meta-Llama3.1-8B</center></h1>"
14
-
15
- PLACEHOLDER = """
16
- <center>
17
- <p>Hi! How can I help you today?</p>
18
- </center>
19
- """
20
-
21
-
22
- CSS = """
23
- .duplicate-button {
24
- margin: auto !important;
25
- color: white !important;
26
- background: black !important;
27
- border-radius: 100vh !important;
28
- }
29
- h3 {
30
- text-align: center;
31
- }
32
- """
33
-
34
- device = "cuda" # for GPU usage or "cpu" for CPU usage
35
-
36
- quantization_config = BitsAndBytesConfig(
37
- load_in_4bit=True,
38
- bnb_4bit_compute_dtype=torch.bfloat16,
39
- bnb_4bit_use_double_quant=True,
40
- bnb_4bit_quant_type= "nf4")
41
-
42
- tokenizer = AutoTokenizer.from_pretrained(MODEL)
43
- model = AutoModelForCausalLM.from_pretrained(
44
- MODEL,
45
- torch_dtype=torch.bfloat16,
46
- device_map="auto",
47
- quantization_config=quantization_config)
48
-
49
- @spaces.GPU()
50
- def stream_chat(
51
- message: str,
52
- history: list,
53
- system_prompt: str,
54
- temperature: float = 0.8,
55
- max_new_tokens: int = 1024,
56
- top_p: float = 1.0,
57
- top_k: int = 20,
58
- penalty: float = 1.2,
59
  ):
60
- print(f'message: {message}')
61
- print(f'history: {history}')
62
-
63
- conversation = [
64
- {"role": "system", "content": system_prompt}
65
- ]
66
- for prompt, answer in history:
67
- conversation.extend([
68
- {"role": "user", "content": prompt},
69
- {"role": "assistant", "content": answer},
70
- ])
71
-
72
- conversation.append({"role": "user", "content": message})
73
 
74
- input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt").to(model.device)
 
75
 
76
- streamer = TextIteratorStreamer(tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
77
-
78
- generate_kwargs = dict(
79
- input_ids=input_ids,
80
- max_new_tokens = max_new_tokens,
81
- do_sample = False if temperature == 0 else True,
82
- top_p = top_p,
83
- top_k = top_k,
84
- temperature = temperature,
85
- repetition_penalty=penalty,
86
- eos_token_id=[128001,128008,128009],
87
- streamer=streamer,
 
 
 
 
 
 
 
 
 
88
  )
89
-
90
- with torch.no_grad():
91
- thread = Thread(target=model.generate, kwargs=generate_kwargs)
92
- thread.start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- buffer = ""
95
- for new_text in streamer:
96
- buffer += new_text
97
- yield buffer
98
-
99
-
100
- chatbot = gr.Chatbot(height=600, placeholder=PLACEHOLDER)
101
-
102
- with gr.Blocks(css=CSS, theme="soft") as demo:
103
- gr.HTML(TITLE)
104
- gr.DuplicateButton(value="Duplicate Space for private use", elem_classes="duplicate-button")
105
- gr.ChatInterface(
106
- fn=stream_chat,
107
- chatbot=chatbot,
108
- fill_height=True,
109
- additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
110
- additional_inputs=[
111
- gr.Textbox(
112
- value="You are a helpful assistant",
113
- label="System Prompt",
114
- render=False,
115
- ),
116
- gr.Slider(
117
- minimum=0,
118
- maximum=1,
119
- step=0.1,
120
- value=0.8,
121
- label="Temperature",
122
- render=False,
123
- ),
124
- gr.Slider(
125
- minimum=128,
126
- maximum=8192,
127
- step=1,
128
- value=1024,
129
- label="Max new tokens",
130
- render=False,
131
- ),
132
- gr.Slider(
133
- minimum=0.0,
134
- maximum=1.0,
135
- step=0.1,
136
- value=1.0,
137
- label="top_p",
138
- render=False,
139
- ),
140
- gr.Slider(
141
- minimum=1,
142
- maximum=20,
143
- step=1,
144
- value=20,
145
- label="top_k",
146
- render=False,
147
- ),
148
- gr.Slider(
149
- minimum=0.0,
150
- maximum=2.0,
151
- step=0.1,
152
- value=1.2,
153
- label="Repetition penalty",
154
- render=False,
155
- ),
156
- ],
157
- examples=[
158
- ["Help me study vocabulary: write a sentence for me to fill in the blank, and I'll try to pick the correct option."],
159
- ["What are 5 creative things I could do with my kids' art? I don't want to throw them away, but it's also so much clutter."],
160
- ["Tell me a random fun fact about the Roman Empire."],
161
- ["Show me a code snippet of a website's sticky header in CSS and JavaScript."],
162
- ],
163
- cache_examples=False,
164
  )
165
-
166
 
167
  if __name__ == "__main__":
168
- demo.launch()
 
 
 
1
  import spaces
2
+ import os
3
+ import subprocess
4
+ from llama_cpp import Llama
5
+ from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
6
+ from llama_cpp_agent.providers import LlamaCppPythonProvider
7
+ from llama_cpp_agent.chat_history import BasicChatHistory
8
+ from llama_cpp_agent.chat_history.messages import Roles
9
  import gradio as gr
10
+ from huggingface_hub import hf_hub_download
11
+
12
+ huggingface_token = os.getenv("HF_TOKEN")
13
+
14
+ # Download the Meta-Llama-3.1-8B-Instruct model
15
+ hf_hub_download(
16
+ repo_id="itaudit/2024-08-14_V3_394_sample",
17
+ filename="unsloth.Q4_K_M.gguf",
18
+ local_dir="./models",
19
+ token=huggingface_token
20
+ )
21
+
22
+ llm = None
23
+ llm_model = None
24
+
25
+ @spaces.GPU(duration=120)
26
+ def respond(
27
+ message,
28
+ history: list[tuple[str, str]],
29
+ model,
30
+ system_message,
31
+ max_tokens,
32
+ temperature,
33
+ top_p,
34
+ top_k,
35
+ repeat_penalty,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  ):
37
+ chat_template = MessagesFormatterType.GEMMA_2
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ global llm
40
+ global llm_model
41
 
42
+ # Load model only if it's not already loaded or if a new model is selected
43
+ if llm is None or llm_model != model:
44
+ try:
45
+ llm = Llama(
46
+ model_path=f"models/{model}",
47
+ flash_attn=True,
48
+ n_gpu_layers=81, # Adjust based on available GPU resources
49
+ n_batch=1024,
50
+ n_ctx=8192,
51
+ )
52
+ llm_model = model
53
+ except Exception as e:
54
+ return f"Error loading model: {str(e)}"
55
+
56
+ provider = LlamaCppPythonProvider(llm)
57
+
58
+ agent = LlamaCppAgent(
59
+ provider,
60
+ system_prompt=f"{system_message}",
61
+ predefined_messages_formatter_type=chat_template,
62
+ debug_output=True
63
  )
64
+
65
+ settings = provider.get_provider_default_settings()
66
+ settings.temperature = temperature
67
+ settings.top_k = top_k
68
+ settings.top_p = top_p
69
+ settings.max_tokens = max_tokens
70
+ settings.repeat_penalty = repeat_penalty
71
+ settings.stream = True
72
+
73
+ messages = BasicChatHistory()
74
+
75
+ # Add user and assistant messages to the history
76
+ for msn in history:
77
+ user = {'role': Roles.user, 'content': msn[0]}
78
+ assistant = {'role': Roles.assistant, 'content': msn[1]}
79
+ messages.add_message(user)
80
+ messages.add_message(assistant)
81
+
82
+ # Stream the response
83
+ try:
84
+ stream = agent.get_chat_response(
85
+ message,
86
+ llm_sampling_settings=settings,
87
+ chat_history=messages,
88
+ returns_streaming_generator=True,
89
+ print_output=False
90
+ )
91
 
92
+ outputs = ""
93
+ for output in stream:
94
+ outputs += output
95
+ yield outputs
96
+ except Exception as e:
97
+ yield f"Error during response generation: {str(e)}"
98
+
99
+ description = """<p align="center">Using the Meta-Llama-3.1-8B-Instruct Model</p>"""
100
+
101
+ demo = gr.ChatInterface(
102
+ respond,
103
+ additional_inputs=[
104
+ gr.Dropdown([
105
+ 'Meta-Llama-3.1-8B-Instruct-Q5_K_M.gguf'
106
+ ],
107
+ value="Meta-Llama-3.1-8B-Instruct-Q5_K_M.gguf",
108
+ label="Model"
109
+ ),
110
+ gr.Textbox(value="You are a helpful assistant.", label="System message"),
111
+ gr.Slider(minimum=1, maximum=4096, value=2048, step=1, label="Max tokens"),
112
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
113
+ gr.Slider(
114
+ minimum=0.1,
115
+ maximum=1.0,
116
+ value=0.95,
117
+ step=0.05,
118
+ label="Top-p",
119
+ ),
120
+ gr.Slider(
121
+ minimum=0,
122
+ maximum=100,
123
+ value=40,
124
+ step=1,
125
+ label="Top-k",
126
+ ),
127
+ gr.Slider(
128
+ minimum=0.0,
129
+ maximum=2.0,
130
+ value=1.1,
131
+ step=0.1,
132
+ label="Repetition penalty",
133
+ ),
134
+ ],
135
+ retry_btn="Retry",
136
+ undo_btn="Undo",
137
+ clear_btn="Clear",
138
+ submit_btn="Send",
139
+ title="Chat with Meta-Llama-3.1-8B-Instruct using llama.cpp",
140
+ description=description,
141
+ chatbot=gr.Chatbot(
142
+ scale=1,
143
+ likeable=False,
144
+ show_copy_button=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  )
146
+ )
147
 
148
  if __name__ == "__main__":
149
+ demo.launch()