Spaces:
Running
Running
File size: 11,040 Bytes
9482433 805fa9c 9482433 805fa9c 9482433 805fa9c 9482433 805fa9c 9482433 805fa9c 9482433 805fa9c 9482433 805fa9c 9482433 805fa9c 9482433 805fa9c 9482433 805fa9c 9482433 805fa9c 9482433 |
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 |
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
class MultiModelChat:
def __init__(self):
self.models = {}
def ensure_model_loaded(self, model_name):
"""Lazy load a model only when needed"""
if model_name not in self.models:
print(f"Loading {model_name} model...")
if model_name == 'SmolLM2':
self.models['SmolLM2'] = {
'tokenizer': AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct"),
'model': AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
}
elif model_name == 'NanoLM-25M':
self.models['NanoLM-25M'] = {
'tokenizer': AutoTokenizer.from_pretrained("Mxode/NanoLM-25M-Instruct-v1.1"),
'model': AutoModelForCausalLM.from_pretrained("Mxode/NanoLM-25M-Instruct-v1.1")
}
elif model_name == 'NanoTranslator-S':
self.models['NanoTranslator-S'] = {
'tokenizer': AutoTokenizer.from_pretrained("Mxode/NanoTranslator-S"),
'model': AutoModelForCausalLM.from_pretrained("Mxode/NanoTranslator-S")
}
elif model_name == 'NanoTranslator-XL':
self.models['NanoTranslator-XL'] = {
'tokenizer': AutoTokenizer.from_pretrained("Mxode/NanoTranslator-XL"),
'model': AutoModelForCausalLM.from_pretrained("Mxode/NanoTranslator-XL")
}
# Set pad token for the newly loaded model
if self.models[model_name]['tokenizer'].pad_token is None:
self.models[model_name]['tokenizer'].pad_token = self.models[model_name]['tokenizer'].eos_token
print(f"{model_name} model loaded successfully!")
def chat(self, message, history, model_choice):
if model_choice == "SmolLM2":
return self.chat_smol(message, history)
elif model_choice == "NanoLM-25M":
return self.chat_nanolm(message, history)
elif model_choice == "NanoTranslator-S":
return self.chat_translator(message, history)
elif model_choice == "NanoTranslator-XL":
return self.chat_translator_xl(message, history)
def chat_smol(self, message, history):
self.ensure_model_loaded('SmolLM2')
tokenizer = self.models['SmolLM2']['tokenizer']
model = self.models['SmolLM2']['model']
inputs = tokenizer(f"User: {message}\nAssistant:", return_tensors="pt")
outputs = model.generate(
inputs.input_ids,
max_new_tokens=80,
temperature=0.7,
do_sample=True,
pad_token_id=tokenizer.eos_token_id
)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
return response.split("Assistant:")[-1].strip()
def chat_nanolm(self, message, history):
self.ensure_model_loaded('NanoLM-25M')
tokenizer = self.models['NanoLM-25M']['tokenizer']
model = self.models['NanoLM-25M']['model']
# Use chat template for NanoLM
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": message}
]
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
inputs = tokenizer([text], return_tensors="pt")
outputs = model.generate(
inputs.input_ids,
max_new_tokens=100,
temperature=0.7,
do_sample=True,
pad_token_id=tokenizer.eos_token_id
)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs.input_ids, outputs)
]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
return response
def chat_translator(self, message, history):
self.ensure_model_loaded('NanoTranslator-S')
tokenizer = self.models['NanoTranslator-S']['tokenizer']
model = self.models['NanoTranslator-S']['model']
# Use translation prompt format
prompt = f"<|im_start|>{message}<|endoftext|>"
inputs = tokenizer([prompt], return_tensors="pt")
outputs = model.generate(
inputs.input_ids,
max_new_tokens=100,
temperature=0.55,
do_sample=True,
pad_token_id=tokenizer.eos_token_id
)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs.input_ids, outputs)
]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
return response
def chat_translator_xl(self, message, history):
self.ensure_model_loaded('NanoTranslator-XL')
tokenizer = self.models['NanoTranslator-XL']['tokenizer']
model = self.models['NanoTranslator-XL']['model']
# Use translation prompt format
prompt = f"<|im_start|>{message}<|endoftext|>"
inputs = tokenizer([prompt], return_tensors="pt")
outputs = model.generate(
inputs.input_ids,
max_new_tokens=100,
temperature=0.55,
do_sample=True,
pad_token_id=tokenizer.eos_token_id
)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs.input_ids, outputs)
]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
return response
chat_app = MultiModelChat()
def respond(message, history, model_choice):
return chat_app.chat(message, history, model_choice)
with gr.Blocks(theme="soft") as demo:
gr.Markdown("# π€ Multi-Model Tiny Chatbot")
gr.Markdown("*Lightweight AI models for different tasks - Choose the right model for your needs!*")
with gr.Row():
model_dropdown = gr.Dropdown(
choices=["SmolLM2", "NanoLM-25M", "NanoTranslator-S", "NanoTranslator-XL"],
value="NanoLM-25M",
label="Select Model",
info="Choose the best model for your task"
)
# Model information display
with gr.Row():
model_info = gr.Markdown(
"""
## π NanoLM-25M (25M) - Selected
**Best for:** Quick responses, simple tasks, resource-constrained environments
**Language:** English
**Memory:** ~100MB
**Speed:** Very Fast
π‘ **Tip:** Ultra-lightweight model perfect for fast responses!
""",
visible=True
)
chatbot = gr.Chatbot(height=400, show_label=False)
msg = gr.Textbox(
label="Message",
placeholder="Type your message here...",
lines=2
)
with gr.Row():
clear = gr.Button("ποΈ Clear Chat", variant="secondary")
submit = gr.Button("π¬ Send", variant="primary")
# Usage tips
with gr.Accordion("π Model Usage Guide", open=False):
gr.Markdown("""
### π― When to use each model:
**π΅ SmolLM2 (135M)**
- General conversations and questions
- Creative writing tasks
- Coding help and explanations
- Educational content
**π’ NanoLM-25M (25M)**
- Quick responses when speed matters
- Resource-constrained environments
- Simple Q&A tasks
- Mobile or edge deployment
**π΄ NanoTranslator-S (9M)**
- Fast English β Chinese translation
- Basic translation needs
- Ultra-low memory usage
- Real-time translation
**π‘ NanoTranslator-XL (78M)**
- High-quality English β Chinese translation
- Professional translation work
- Complex sentences and idioms
- Better context understanding
### π‘ Pro Tips:
- Models load automatically when first selected (lazy loading)
- Translation models work best with clear, complete sentences
- For translation, input English text and get Chinese output
- Restart the app to free up memory from unused models
""")
def update_model_info(model_choice):
info_map = {
"SmolLM2": """
## π SmolLM2 (135M) - Selected
**Best for:** General conversation, Q&A, creative writing, coding help
**Language:** English
**Memory:** ~500MB
**Speed:** Fast
π‘ **Tip:** Great all-around model for most conversational tasks!
""",
"NanoLM-25M": """
## π NanoLM-25M (25M) - Selected
**Best for:** Quick responses, simple tasks, resource-constrained environments
**Language:** English
**Memory:** ~100MB
**Speed:** Very Fast
π‘ **Tip:** Ultra-lightweight model perfect for fast responses!
""",
"NanoTranslator-S": """
## π NanoTranslator-S (9M) - Selected
**Best for:** Fast English β Chinese translation
**Language:** English β Chinese
**Memory:** ~50MB
**Speed:** Very Fast
π‘ **Tip:** Input English text to get Chinese translation. Great for quick translations!
""",
"NanoTranslator-XL": """
## π NanoTranslator-XL (78M) - Selected
**Best for:** High-quality English β Chinese translation
**Language:** English β Chinese
**Memory:** ~300MB
**Speed:** Fast
π‘ **Tip:** Best translation quality for complex sentences and professional use!
"""
}
return info_map.get(model_choice, "")
# Update model info when dropdown changes
model_dropdown.change(
update_model_info,
inputs=[model_dropdown],
outputs=[model_info]
)
def user_message(message, history):
return "", history + [[message, None]]
def bot_message(history, model_choice):
user_msg = history[-1][0]
bot_response = chat_app.chat(user_msg, history[:-1], model_choice)
history[-1][1] = bot_response
return history
# Handle message submission
msg.submit(user_message, [msg, chatbot], [msg, chatbot]).then(
bot_message, [chatbot, model_dropdown], chatbot
)
submit.click(user_message, [msg, chatbot], [msg, chatbot]).then(
bot_message, [chatbot, model_dropdown], chatbot
)
clear.click(lambda: None, None, chatbot, queue=False)
demo.launch() |