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+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
| 4 |
+
from threading import Thread
|
| 5 |
+
from transformers import TextIteratorStreamer
|
| 6 |
+
|
| 7 |
+
# Language-specific system prompts (extracted from training set)
|
| 8 |
+
LANGUAGE_SYSTEM_PROMPTS = {
|
| 9 |
+
# Germanic languages
|
| 10 |
+
"en": "You are a helpful AI assistant.",
|
| 11 |
+
"de": "Sie sind ein hilfreicher KI-Assistent.",
|
| 12 |
+
"nl": "Je bent een behulpzame AI-assistent.",
|
| 13 |
+
"da": "Du er en hjælpsom AI-assistent.",
|
| 14 |
+
"sv": "Du är en hjälpsam AI-assistent.",
|
| 15 |
+
"no": "Du er en hjelpsom AI-assistent.",
|
| 16 |
+
|
| 17 |
+
# Romance languages
|
| 18 |
+
"fr": "Vous êtes un assistant IA utile.",
|
| 19 |
+
"es": "Eres un asistente de IA útil.",
|
| 20 |
+
"it": "Sei un assistente AI utile.",
|
| 21 |
+
"pt": "Você é um assistente de IA prestativo.",
|
| 22 |
+
"ro": "Ești un asistent AI de ajutor.",
|
| 23 |
+
|
| 24 |
+
# Slavic languages
|
| 25 |
+
"pl": "Jesteś pomocnym asystentem AI.",
|
| 26 |
+
"cs": "Jste užitečný AI asistent.",
|
| 27 |
+
"sk": "Ste užitočný AI asistent.",
|
| 28 |
+
"bg": "Вие сте полезен AI асистент.",
|
| 29 |
+
"hr": "Vi ste korisni AI asistent.",
|
| 30 |
+
"sl": "Vi ste koristen AI asistent.",
|
| 31 |
+
|
| 32 |
+
# Baltic languages
|
| 33 |
+
"lv": "Tu esi izpalīdzīgs mākslīgā intelekta asistents.",
|
| 34 |
+
"lt": "Jūs esate naudingas dirbtinio intelekto asistentas.",
|
| 35 |
+
"et": "Olete abivalmis tehisintellekti assistent.",
|
| 36 |
+
|
| 37 |
+
# Other European languages
|
| 38 |
+
"fi": "Olet avulias tekoälyavustaja.",
|
| 39 |
+
"hu": "Ön egy segítőkész AI asszisztens.",
|
| 40 |
+
"el": "Είστε ένας χρήσιμος βοηθός AI.",
|
| 41 |
+
"mt": "Inti assistent tal-AI utli.",
|
| 42 |
+
|
| 43 |
+
# Eastern European
|
| 44 |
+
"ru": "Вы полезный ИИ-ассистент.",
|
| 45 |
+
"uk": "Ви корисний AI-асистент.",
|
| 46 |
+
|
| 47 |
+
# Asian languages (if needed)
|
| 48 |
+
"zh": "你是一个有用的AI助手。",
|
| 49 |
+
"ja": "あなたは役に立つAIアシスタントです。",
|
| 50 |
+
"ko": "당신은 유용한 AI 어시스턴트입니다.",
|
| 51 |
+
"hi": "आप एक उपयोगी एआई सहायक हैं।",
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
# Model loading
|
| 55 |
+
MODEL_PATH = "martinsu/tildeopen-30b-mu-instruct"
|
| 56 |
+
|
| 57 |
+
print(f"Loading model from {MODEL_PATH}...")
|
| 58 |
+
|
| 59 |
+
# Configure 4-bit quantization for memory efficiency
|
| 60 |
+
quantization_config = BitsAndBytesConfig(
|
| 61 |
+
load_in_4bit=True,
|
| 62 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 63 |
+
bnb_4bit_quant_type="nf4",
|
| 64 |
+
bnb_4bit_use_double_quant=True, # Nested quantization for extra memory savings
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_fast=False)
|
| 68 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 69 |
+
MODEL_PATH,
|
| 70 |
+
quantization_config=quantization_config,
|
| 71 |
+
device_map="auto",
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
print("Model loaded!")
|
| 75 |
+
|
| 76 |
+
def chat(message, history, temperature, language):
|
| 77 |
+
"""Generate response with configurable temperature and language."""
|
| 78 |
+
# Gradio ChatInterface passes history with content as string or list[dict]
|
| 79 |
+
# Extract text content for apply_chat_template
|
| 80 |
+
def extract_text(content):
|
| 81 |
+
if isinstance(content, str):
|
| 82 |
+
return content
|
| 83 |
+
elif isinstance(content, list):
|
| 84 |
+
# List of content items: [{"type": "text", "text": "..."}]
|
| 85 |
+
texts = [item.get("text", "") for item in content if isinstance(item, dict) and item.get("type") == "text"]
|
| 86 |
+
return " ".join(texts)
|
| 87 |
+
return ""
|
| 88 |
+
|
| 89 |
+
# Get system prompt for selected language
|
| 90 |
+
system_prompt = LANGUAGE_SYSTEM_PROMPTS.get(language, LANGUAGE_SYSTEM_PROMPTS["en"])
|
| 91 |
+
|
| 92 |
+
# Build messages with system prompt and text-only content
|
| 93 |
+
messages = [{"role": "system", "content": system_prompt}]
|
| 94 |
+
messages.extend([{"role": msg["role"], "content": extract_text(msg["content"])} for msg in history])
|
| 95 |
+
messages.append({"role": "user", "content": extract_text(message) if not isinstance(message, str) else message})
|
| 96 |
+
|
| 97 |
+
# Apply chat template (tokenizer handles the formatting)
|
| 98 |
+
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 99 |
+
|
| 100 |
+
# Tokenize
|
| 101 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 102 |
+
|
| 103 |
+
# Generate with streaming
|
| 104 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 105 |
+
generation_kwargs = dict(
|
| 106 |
+
inputs,
|
| 107 |
+
streamer=streamer,
|
| 108 |
+
max_new_tokens=512,
|
| 109 |
+
temperature=temperature,
|
| 110 |
+
top_p=0.9,
|
| 111 |
+
do_sample=True
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
| 115 |
+
thread.start()
|
| 116 |
+
|
| 117 |
+
partial = ""
|
| 118 |
+
for new_text in streamer:
|
| 119 |
+
partial += new_text
|
| 120 |
+
yield partial
|
| 121 |
+
|
| 122 |
+
# Prepare language options (sorted by priority)
|
| 123 |
+
language_options = [
|
| 124 |
+
("English", "en"),
|
| 125 |
+
("Latviešu (Latvian)", "lv"),
|
| 126 |
+
("Deutsch (German)", "de"),
|
| 127 |
+
("Français (French)", "fr"),
|
| 128 |
+
("Español (Spanish)", "es"),
|
| 129 |
+
("Italiano (Italian)", "it"),
|
| 130 |
+
("Polski (Polish)", "pl"),
|
| 131 |
+
("Português (Portuguese)", "pt"),
|
| 132 |
+
("Nederlands (Dutch)", "nl"),
|
| 133 |
+
("Svenska (Swedish)", "sv"),
|
| 134 |
+
("Česky (Czech)", "cs"),
|
| 135 |
+
("Română (Romanian)", "ro"),
|
| 136 |
+
("Dansk (Danish)", "da"),
|
| 137 |
+
("Suomi (Finnish)", "fi"),
|
| 138 |
+
("Magyar (Hungarian)", "hu"),
|
| 139 |
+
("Ελληνικά (Greek)", "el"),
|
| 140 |
+
("Български (Bulgarian)", "bg"),
|
| 141 |
+
("Lietuvių (Lithuanian)", "lt"),
|
| 142 |
+
("Eesti (Estonian)", "et"),
|
| 143 |
+
("Русский (Russian)", "ru"),
|
| 144 |
+
]
|
| 145 |
+
|
| 146 |
+
# Chat interface with additional inputs always visible
|
| 147 |
+
demo = gr.ChatInterface(
|
| 148 |
+
chat,
|
| 149 |
+
title="TildeOpen-30B Chat",
|
| 150 |
+
description="Multilingual chat model supporting European languages (4-bit quantized), please select appropriate system prompt language (Swedish, Latvian, Estonian), default is English, that will help model to predict more desirable tokens.",
|
| 151 |
+
additional_inputs=[
|
| 152 |
+
gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.1, label="Temperature"),
|
| 153 |
+
gr.Dropdown(choices=language_options, value="en", label="Language / System Prompt"),
|
| 154 |
+
],
|
| 155 |
+
additional_inputs_accordion=gr.Accordion(label="⚙️ Settings", open=True),
|
| 156 |
+
submit_btn=True,
|
| 157 |
+
stop_btn=True,
|
| 158 |
+
autofocus=True,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
if __name__ == "__main__":
|
| 162 |
+
demo.launch()
|