Spaces:
Sleeping
Sleeping
File size: 9,633 Bytes
5e5249d f7fb6bc 5e5249d 3080342 5e5249d f7fb6bc 5e5249d 2e33ec7 f7fb6bc dd0c774 5e5249d dd0c774 f7fb6bc d816a8a bb12293 d816a8a bb12293 d816a8a 2e33ec7 bb12293 f492dde 2e33ec7 d816a8a f492dde bb12293 5e5249d bb12293 5e5249d bb12293 2e33ec7 bb12293 2e33ec7 bb12293 5e5249d f7fb6bc dd0c774 5e5249d dd0c774 5e5249d dd0c774 5e5249d dd0c774 5e5249d f7fb6bc 5e5249d f7fb6bc bb12293 2e33ec7 bb12293 d816a8a 2e33ec7 bb12293 2e33ec7 f7fb6bc 2e33ec7 5e5249d d816a8a 2e33ec7 bb12293 2e33ec7 bb12293 2e33ec7 bb12293 d816a8a 2e33ec7 f7fb6bc 2e33ec7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
import os
from threading import Thread
from typing import Iterator
import gradio as gr
import spaces
import torch
import json
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
DESCRIPTION = """\
Shakti LLMs (Large Language Models) are a group of compact language models specifically optimized for resource-constrained environments such as edge devices, including smartphones, wearables, and IoT (Internet of Things) systems. These models provide support for vernacular languages and domain-specific tasks, making them particularly suitable for industries such as healthcare, finance, and customer service.
For more details, please check [here](https://arxiv.org/pdf/2410.11331v1)
"""
# """\
# Shakti LLMs are a group of small language model specifically optimized for resource-constrained environments such as edge devices, including smartphones, wearables, and IoT systems. With support for vernacular languages and domain-specific tasks, Shakti excels in industries such as healthcare, finance, and customer service.
# For more details, please check [here](https://arxiv.org/pdf/2410.11331v1).
# """
# Custom CSS for the send button
CUSTOM_CSS = """
.send-btn {
padding: 0.5rem !important;
width: 55px !important;
height: 55px !important;
border-radius: 50% !important;
margin-top: 1rem;
cursor: pointer;
}
.send-btn svg {
width: 20px !important;
height: 20px !important;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
"""
MAX_MAX_NEW_TOKENS = 2048
DEFAULT_MAX_NEW_TOKENS = 1024
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "2048"))
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Model configurations
model_options = {
"Shakti-100M": "SandLogicTechnologies/Shakti-100M",
"Shakti-250M": "SandLogicTechnologies/Shakti-250M",
"Shakti-2.5B": "SandLogicTechnologies/Shakti-2.5B"
}
# Initialize tokenizer and model variables
tokenizer = None
model = None
current_model = "Shakti-2.5B" # Keep track of current model
def load_model(selected_model: str):
global tokenizer, model, current_model
model_id = model_options[selected_model]
tokenizer = AutoTokenizer.from_pretrained(model_id, token=os.getenv("SHAKTI"))
model = AutoModelForCausalLM.from_pretrained(
model_id,
device_map="auto",
torch_dtype=torch.bfloat16,
token=os.getenv("SHAKTI")
)
model.eval()
print("Selected Model: ", selected_model)
current_model = selected_model
# Initial model load
load_model("Shakti-2.5B")
def generate(
message: str,
chat_history: list[tuple[str, str]],
max_new_tokens: int = 1024,
temperature: float = 0.6,
top_p: float = 0.9,
top_k: int = 50,
repetition_penalty: float = 1.2,
) -> Iterator[str]:
conversation = []
if current_model == "Shakti-2.5B":
for user, assistant in chat_history:
conversation.extend([
json.loads(os.getenv("PROMPT")),
{"role": "user", "content": user},
{"role": "assistant", "content": assistant},
])
else:
for user, assistant in chat_history:
conversation.extend([
{"role": "user", "content": user},
{"role": "assistant", "content": assistant},
])
conversation.append({"role": "user", "content": message})
input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
input_ids = input_ids.to(model.device)
streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
generate_kwargs = dict(
{"input_ids": input_ids},
streamer=streamer,
max_new_tokens=max_new_tokens,
do_sample=True,
top_p=top_p,
top_k=top_k,
temperature=temperature,
num_beams=1,
repetition_penalty=repetition_penalty,
)
t = Thread(target=model.generate, kwargs=generate_kwargs)
t.start()
outputs = []
for text in streamer:
outputs.append(text)
yield "".join(outputs)
def respond(message, chat_history, max_new_tokens, temperature):
bot_message = ""
for chunk in generate(message, chat_history, max_new_tokens, temperature):
bot_message += chunk
chat_history.append((message, bot_message))
return "", chat_history
def get_examples(selected_model):
examples = {
"Shakti-100M": [
["Tell me a story"],
["Write a short poem on Rose"],
["What are computers"]
],
"Shakti-250M": [
["Can you explain the pathophysiology of hypertension and its impact on the cardiovascular system?"],
["What are the potential side effects of beta-blockers in the treatment of arrhythmias?"],
["What foods are good for boosting the immune system?"],
["What is the difference between a stock and a bond?"],
["How can I start saving for retirement?"],
["What are some low-risk investment options?"]
],
"Shakti-2.5B": [
["Tell me a story"],
["write a short poem which is hard to sing"],
['मुझे भारतीय इतिहास के बारे में बताएं']
]
}
return examples.get(selected_model, [])
def on_model_select(selected_model):
load_model(selected_model) # Load the selected model
# Return the message and chat history updates
return gr.update(value=""), gr.update(value=[]) # Clear message and chat history
def update_examples_visibility(selected_model):
# Return individual updates for each example section
return (
gr.update(visible=selected_model == "Shakti-100M"),
gr.update(visible=selected_model == "Shakti-250M"),
gr.update(visible=selected_model == "Shakti-2.5B")
)
def example_selector(example):
return example
with gr.Blocks(css=CUSTOM_CSS) as demo:
gr.Markdown(DESCRIPTION)
with gr.Row():
model_dropdown = gr.Dropdown(
label="Select Model",
choices=list(model_options.keys()),
value="Shakti-2.5B",
interactive=True
)
chatbot = gr.Chatbot()
with gr.Row():
with gr.Column(scale=20):
msg = gr.Textbox(
label="Message",
placeholder="Enter your message here",
lines=2,
show_label=False
)
with gr.Column(scale=1, min_width=50):
send_btn = gr.Button(
value="➤",
variant="primary",
elem_classes=["send-btn"]
)
with gr.Accordion("Parameters", open=False):
max_tokens_slider = gr.Slider(
label="Max new tokens",
minimum=1,
maximum=MAX_MAX_NEW_TOKENS,
step=1,
value=DEFAULT_MAX_NEW_TOKENS,
)
temperature_slider = gr.Slider(
label="Temperature",
minimum=0.1,
maximum=4.0,
step=0.1,
value=0.6,
)
# Add submit action handlers
submit_click = send_btn.click(
respond,
inputs=[msg, chatbot, max_tokens_slider, temperature_slider],
outputs=[msg, chatbot]
)
submit_enter = msg.submit(
respond,
inputs=[msg, chatbot, max_tokens_slider, temperature_slider],
outputs=[msg, chatbot]
)
# Create separate example sections for each model
with gr.Row():
with gr.Column(visible=False) as examples_100m:
gr.Examples(
examples=get_examples("Shakti-100M"),
inputs=msg,
label="Example prompts for Shakti-100M",
fn=example_selector
)
with gr.Column(visible=False) as examples_250m:
gr.Examples(
examples=get_examples("Shakti-250M"),
inputs=msg,
label="Example prompts for Shakti-250M",
fn=example_selector
)
with gr.Column(visible=True) as examples_2_5b:
gr.Examples(
examples=get_examples("Shakti-2.5B"),
inputs=msg,
label="Example prompts for Shakti-2.5B",
fn=example_selector
)
# Update model selection and examples visibility
def combined_update(selected_model):
msg_update, chat_update = on_model_select(selected_model)
examples_100m_update, examples_250m_update, examples_2_5b_update = update_examples_visibility(
selected_model)
return [
msg_update,
chat_update,
examples_100m_update,
examples_250m_update,
examples_2_5b_update
]
# Updated change event handler
model_dropdown.change(
combined_update,
inputs=[model_dropdown],
outputs=[
msg,
chatbot,
examples_100m,
examples_250m,
examples_2_5b
]
)
if __name__ == "__main__":
demo.queue(max_size=20).launch() |