Spaces:
Running
on
Zero
Running
on
Zero
File size: 23,949 Bytes
80e6c51 9374cab b15c679 57ec10d bb53eb4 6dffe5a b15c679 80e6c51 cea62b1 5373262 a108184 bb53eb4 8e35c48 bdee432 80e6c51 bb53eb4 80e6c51 bb53eb4 b15c679 bb53eb4 80e6c51 6dffe5a 80e6c51 6dffe5a 80e6c51 3d6db7f 6dffe5a 3d6db7f 6dffe5a cea62b1 6dffe5a 80e6c51 6dffe5a 80e6c51 bb53eb4 80e6c51 bb53eb4 80e6c51 6dffe5a bb53eb4 80e6c51 bb53eb4 9374cab 80e6c51 bb53eb4 80e6c51 6dffe5a 80e6c51 6dffe5a 80e6c51 bb53eb4 6dffe5a 80e6c51 bb53eb4 6dffe5a 80e6c51 bb53eb4 80e6c51 6dffe5a 80e6c51 6dffe5a 80e6c51 bb53eb4 b15c679 9374cab b15c679 80e6c51 bb53eb4 9374cab bb53eb4 80e6c51 6dffe5a ee4073b 80e6c51 6dffe5a b901de9 6dffe5a 80e6c51 6dffe5a b901de9 80e6c51 cea62b1 52d8257 f62afbf 52d8257 bb53eb4 b15c679 cac72ef 80e6c51 bb53eb4 6dffe5a 80e6c51 b15c679 cac72ef b15c679 6dffe5a 3d6db7f b15c679 bb53eb4 b15c679 cac72ef b15c679 bb53eb4 b15c679 80e6c51 b15c679 cac72ef 57ec10d 80e6c51 6dffe5a 80e6c51 6dffe5a b15c679 80e6c51 cea62b1 b15c679 80e6c51 b15c679 cac72ef 80e6c51 bb53eb4 6dffe5a 80e6c51 b15c679 cac72ef b15c679 6dffe5a 3d6db7f b15c679 bb53eb4 b15c679 cac72ef b15c679 bb53eb4 b15c679 80e6c51 b15c679 57ec10d 80e6c51 6dffe5a 80e6c51 b15c679 6dffe5a b15c679 80e6c51 cea62b1 b15c679 80e6c51 751481f b15c679 cac72ef 751481f cac72ef 751481f cac72ef bb53eb4 cac72ef 751481f cac72ef 6dffe5a 3d6db7f b15c679 bb53eb4 b15c679 cac72ef b15c679 bb53eb4 b15c679 751481f b15c679 cac72ef 57ec10d |
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 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 |
import spaces
import gradio as gr
from pathlib import Path
import re
import torch
import gc
import os
import urllib
from typing import Any
from huggingface_hub import hf_hub_download, HfApi
from llama_cpp import Llama
from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
from llama_cpp_agent.providers import LlamaCppPythonProvider
from llama_cpp_agent.chat_history import BasicChatHistory
from llama_cpp_agent.chat_history.messages import Roles
from ja_to_danbooru.ja_to_danbooru import jatags_to_danbooru_tags
import wrapt_timeout_decorator
from llama_cpp_agent.messages_formatter import MessagesFormatter
from formatter import mistral_v1_formatter, mistral_v2_formatter, mistral_v3_tekken_formatter
from llmenv import llm_models, llm_models_dir, llm_loras, llm_loras_dir, llm_formats, llm_languages, dolphin_system_prompt
import subprocess
subprocess.run("rm -rf /data-nvme/zerogpu-offload/*", env={}, shell=True)
llm_models_list = []
llm_loras_list = []
default_llm_model_filename = list(llm_models.keys())[0]
default_llm_lora_filename = list(llm_loras.keys())[0]
device = "cuda" if torch.cuda.is_available() else "cpu"
HF_TOKEN = os.getenv("HF_TOKEN", False)
def to_list(s: str):
return [x.strip() for x in s.split(",") if not s == ""]
def list_uniq(l: list):
return sorted(set(l), key=l.index)
DEFAULT_STATE = {
"dolphin_sysprompt_mode": "Default",
"dolphin_output_language": llm_languages[0],
}
def get_state(state: dict, key: str):
if key in state.keys(): return state[key]
elif key in DEFAULT_STATE.keys():
print(f"State '{key}' not found. Use dedault value.")
return DEFAULT_STATE[key]
else:
print(f"State '{key}' not found.")
return None
def set_state(state: dict, key: str, value: Any):
state[key] = value
@wrapt_timeout_decorator.timeout(dec_timeout=3.5)
def to_list_ja(s: str):
s = re.sub(r'[γγ]', ',', s)
return [x.strip() for x in s.split(",") if not s == ""]
def is_japanese(s: str):
import unicodedata
for ch in s:
name = unicodedata.name(ch, "")
if "CJK UNIFIED" in name or "HIRAGANA" in name or "KATAKANA" in name:
return True
return False
def get_dir_size(path: str):
total = 0
with os.scandir(path) as it:
for entry in it:
if entry.is_file():
total += entry.stat().st_size
elif entry.is_dir():
total += get_dir_size(entry.path)
return total
def get_dir_size_gb(path: str):
try:
size_gb = get_dir_size(path) / (1024 ** 3)
print(f"Dir size: {size_gb:.2f} GB ({path})")
except Exception as e:
size_gb = 999
print(f"Error while retrieving the used storage: {e}.")
finally:
return size_gb
def clean_dir(path: str, size_gb: float, limit_gb: float):
try:
files = os.listdir(path)
files = [os.path.join(path, f) for f in files if f.endswith(".gguf") and default_llm_model_filename not in f and default_llm_lora_filename not in f]
files.sort(key=os.path.getatime, reverse=False)
req_bytes = int((size_gb - limit_gb) * (1024 ** 3))
for file in files:
if req_bytes < 0: break
size = os.path.getsize(file)
Path(file).unlink()
req_bytes -= size
print(f"Deleted: {file}")
except Exception as e:
print(e)
def update_storage(path: str, limit_gb: float=50.0):
size_gb = get_dir_size_gb(path)
if size_gb > limit_gb:
print("Cleaning storage...")
clean_dir(path, size_gb, limit_gb)
#get_dir_size_gb(path)
def split_hf_url(url: str):
try:
s = list(re.findall(r'^(?:https?://huggingface.co/)(?:(datasets|spaces)/)?(.+?/.+?)/\w+?/.+?/(?:(.+)/)?(.+?.\w+)(?:\?download=true)?$', url)[0])
if len(s) < 4: return "", "", "", ""
repo_id = s[1]
if s[0] == "datasets": repo_type = "dataset"
elif s[0] == "spaces": repo_type = "space"
else: repo_type = "model"
subfolder = urllib.parse.unquote(s[2]) if s[2] else None
filename = urllib.parse.unquote(s[3])
return repo_id, filename, subfolder, repo_type
except Exception as e:
print(e)
def hf_url_exists(url: str):
hf_token = HF_TOKEN
repo_id, filename, subfolder, repo_type = split_hf_url(url)
api = HfApi(token=hf_token)
return api.file_exists(repo_id=repo_id, filename=filename, repo_type=repo_type, token=hf_token)
def get_repo_type(repo_id: str):
try:
api = HfApi(token=HF_TOKEN)
if api.repo_exists(repo_id=repo_id, repo_type="dataset", token=HF_TOKEN): return "dataset"
elif api.repo_exists(repo_id=repo_id, repo_type="space", token=HF_TOKEN): return "space"
elif api.repo_exists(repo_id=repo_id, token=HF_TOKEN): return "model"
else: return None
except Exception as e:
print(e)
raise Exception(f"Repo not found: {repo_id} {e}")
def get_hf_blob_url(repo_id: str, repo_type: str, path: str):
if repo_type == "model": return f"https://huggingface.co/{repo_id}/blob/main/{path}"
elif repo_type == "dataset": return f"https://huggingface.co/datasets/{repo_id}/blob/main/{path}"
elif repo_type == "space": return f"https://huggingface.co/spaces/{repo_id}/blob/main/{path}"
def get_gguf_url(s: str):
def find_gguf(d: dict, keys: dict):
paths = []
for key, size in keys.items():
if size != 0: l = [p for p, s in d.items() if key.lower() in p.lower() and s < size]
else: l = [p for p in d.keys() if key.lower() in p.lower()]
if len(l) > 0: paths.append(l[0])
if len(paths) > 0: return paths[0]
return list(d.keys())[0]
try:
if s.lower().endswith(".gguf"): return s
repo_type = get_repo_type(s)
if repo_type is None: return s
repo_id = s
api = HfApi(token=HF_TOKEN)
gguf_dict = {i.path: i.size for i in api.list_repo_tree(repo_id=repo_id, repo_type=repo_type, recursive=True, token=HF_TOKEN) if i.path.endswith(".gguf")}
if len(gguf_dict) == 0: return s
return get_hf_blob_url(repo_id, repo_type, find_gguf(gguf_dict, {"Q5_K_M": 6000000000, "Q4_K_M": 0, "Q4": 0}))
except Exception as e:
print(e)
return s
def download_hf_file(directory, url, progress=gr.Progress(track_tqdm=True)):
hf_token = HF_TOKEN
repo_id, filename, subfolder, repo_type = split_hf_url(url)
try:
print(f"Downloading {url} to {directory}")
if subfolder is not None: path = hf_hub_download(repo_id=repo_id, filename=filename, subfolder=subfolder, repo_type=repo_type, local_dir=directory, token=hf_token)
else: path = hf_hub_download(repo_id=repo_id, filename=filename, repo_type=repo_type, local_dir=directory, token=hf_token)
return path
except Exception as e:
print(f"Failed to download: {e}")
return None
def update_llm_model_list():
global llm_models_list
llm_models_list = []
for k in llm_models.keys():
llm_models_list.append(k)
model_files = Path(llm_models_dir).glob('*.gguf')
for path in model_files:
llm_models_list.append(path.name)
llm_models_list = list_uniq(llm_models_list)
return llm_models_list
def download_llm_model(filename: str):
if filename not in llm_models.keys(): return default_llm_model_filename
try:
hf_hub_download(repo_id=llm_models[filename][0], filename=filename, local_dir=llm_models_dir, token=HF_TOKEN)
except Exception as e:
print(e)
return default_llm_model_filename
update_llm_model_list()
return filename
def update_llm_lora_list():
global llm_loras_list
llm_loras_list = list(llm_loras.keys()).copy()
model_files = Path(llm_loras_dir).glob('*.gguf')
for path in model_files:
llm_loras_list.append(path.name)
llm_loras_list = list_uniq([""] + llm_loras_list)
return llm_loras_list
def download_llm_lora(filename: str):
if not filename in llm_loras.keys(): return ""
try:
download_hf_file(llm_loras_dir, llm_loras[filename])
except Exception as e:
print(e)
return ""
update_llm_lora_list()
return filename
def get_dolphin_model_info(filename: str):
md = "None"
items = llm_models.get(filename, None)
if items:
md = f'Repo: [{items[0]}](https://huggingface.co/{items[0]})'
return md
def select_dolphin_model(filename: str, state: dict, progress=gr.Progress(track_tqdm=True)):
set_state(state, "override_llm_format", None)
progress(0, desc="Loading model...")
value = download_llm_model(filename)
progress(1, desc="Model loaded.")
md = get_dolphin_model_info(filename)
update_storage(llm_models_dir)
return gr.update(value=value, choices=get_dolphin_models()), gr.update(value=get_dolphin_model_format(value)), gr.update(value=md), state
def select_dolphin_lora(filename: str, state: dict, progress=gr.Progress(track_tqdm=True)):
progress(0, desc="Loading lora...")
value = download_llm_lora(filename)
progress(1, desc="Lora loaded.")
update_storage(llm_loras_dir)
return gr.update(value=value, choices=get_dolphin_loras()), state
def select_dolphin_format(format_name: str, state: dict):
set_state(state, "override_llm_format", llm_formats[format_name])
return gr.update(value=format_name), state
download_llm_model(default_llm_model_filename)
def get_dolphin_models():
return update_llm_model_list()
def get_dolphin_loras():
return update_llm_lora_list()
def get_llm_formats():
return list(llm_formats.keys())
def get_key_from_value(d, val):
keys = [k for k, v in d.items() if v == val]
if keys:
return keys[0]
return None
def get_dolphin_model_format(filename: str):
if not filename in llm_models.keys(): filename = default_llm_model_filename
format = llm_models[filename][1]
format_name = get_key_from_value(llm_formats, format)
return format_name
def add_dolphin_models(query: str, format_name: str):
global llm_models
try:
add_models = {}
format = llm_formats[format_name]
filename = ""
repo = ""
query = get_gguf_url(query)
if hf_url_exists(query):
s = list(re.findall(r'^https?://huggingface.co/(.+?/.+?)/(?:blob|resolve)/main/(.+.gguf)(?:\?download=true)?$', query)[0])
if len(s) == 2:
repo = s[0]
filename = s[1]
add_models[filename] = [repo, format]
else: return gr.update()
except Exception as e:
print(e)
return gr.update()
llm_models = (llm_models | add_models).copy()
update_llm_model_list()
choices = get_dolphin_models()
return gr.update(choices=choices, value=choices[-1])
def add_dolphin_loras(query: str):
global llm_loras
try:
add_loras = {}
query = get_gguf_url(query)
if hf_url_exists(query): add_loras[Path(query).name] = query
except Exception as e:
print(e)
return gr.update()
llm_loras = (llm_loras | add_loras).copy()
update_llm_lora_list()
choices = get_dolphin_loras()
return gr.update(choices=choices, value=choices[-1])
def get_dolphin_sysprompt(state: dict={}):
dolphin_sysprompt_mode = get_state(state, "dolphin_sysprompt_mode")
dolphin_output_language = get_state(state, "dolphin_output_language")
prompt = re.sub('<LANGUAGE>', dolphin_output_language if dolphin_output_language else llm_languages[0],
dolphin_system_prompt.get(dolphin_sysprompt_mode, dolphin_system_prompt[list(dolphin_system_prompt.keys())[0]]))
return prompt
def get_dolphin_sysprompt_mode():
return list(dolphin_system_prompt.keys())
def select_dolphin_sysprompt(key: str, state: dict):
dolphin_sysprompt_mode = get_state(state, "dolphin_sysprompt_mode")
if not key in dolphin_system_prompt.keys(): dolphin_sysprompt_mode = "Default"
else: dolphin_sysprompt_mode = key
set_state(state, "dolphin_sysprompt_mode", dolphin_sysprompt_mode)
return gr.update(value=get_dolphin_sysprompt(state)), state
def get_dolphin_languages():
return llm_languages
def select_dolphin_language(lang: str, state: dict):
set_state(state, "dolphin_output_language", lang)
return gr.update(value=get_dolphin_sysprompt(state)), state
@wrapt_timeout_decorator.timeout(dec_timeout=5.0)
def get_raw_prompt(msg: str):
m = re.findall(r'/GENBEGIN/(.+?)/GENEND/', msg, re.DOTALL)
return re.sub(r'[*/:_"#\n]', ' ', ", ".join(m)).lower() if m else ""
# https://llama-cpp-python.readthedocs.io/en/latest/api-reference/
@torch.inference_mode()
@spaces.GPU(duration=59)
def dolphin_respond(
message: str,
history: list[tuple[str, str]],
model: str = default_llm_model_filename,
system_message: str = get_dolphin_sysprompt(),
max_tokens: int = 1024,
temperature: float = 0.7,
top_p: float = 0.95,
top_k: int = 40,
repeat_penalty: float = 1.1,
lora: str = "",
lora_scale: float = 1.0,
state: dict = {},
progress=gr.Progress(track_tqdm=True),
):
try:
model_path = Path(f"{llm_models_dir}/{model}")
if not model_path.exists(): raise gr.Error(f"Model file not found: {str(model_path)}")
progress(0, desc="Processing...")
override_llm_format = get_state(state, "override_llm_format")
if override_llm_format: chat_template = override_llm_format
else: chat_template = llm_models[model][1]
kwargs = {}
if lora:
kwargs["lora_path"] = str(Path(f"{llm_loras_dir}/{lora}"))
kwargs["lora_scale"] = lora_scale
else:
kwargs["flash_attn"] = True
llm = Llama(
model_path=str(model_path),
n_gpu_layers=81, # 81
n_batch=1024,
n_ctx=8192, #8192
**kwargs,
)
provider = LlamaCppPythonProvider(llm)
agent = LlamaCppAgent(
provider,
system_prompt=f"{system_message}",
predefined_messages_formatter_type=chat_template if not isinstance(chat_template, MessagesFormatter) else None,
custom_messages_formatter=chat_template if isinstance(chat_template, MessagesFormatter) else None,
debug_output=False
)
settings = provider.get_provider_default_settings()
settings.temperature = temperature
settings.top_k = top_k
settings.top_p = top_p
settings.max_tokens = max_tokens
settings.repeat_penalty = repeat_penalty
settings.stream = True
messages = BasicChatHistory()
for msn in history:
user = {
'role': Roles.user,
'content': msn[0]
}
assistant = {
'role': Roles.assistant,
'content': msn[1]
}
messages.add_message(user)
messages.add_message(assistant)
stream = agent.get_chat_response(
message,
llm_sampling_settings=settings,
chat_history=messages,
returns_streaming_generator=True,
print_output=False
)
progress(0.5, desc="Processing...")
outputs = ""
for output in stream:
outputs += output
yield [(outputs, None)]
except Exception as e:
print(e)
raise gr.Error(f"Error: {e}")
#yield [("", None)]
finally:
torch.cuda.empty_cache()
gc.collect()
def dolphin_parse(
history: list[tuple[str, str]],
state: dict,
):
try:
dolphin_sysprompt_mode = get_state(state, "dolphin_sysprompt_mode")
if dolphin_sysprompt_mode == "Chat with LLM" or not history or len(history) < 1:
return "", gr.update(), gr.update()
msg = history[-1][0]
raw_prompt = get_raw_prompt(msg)
prompts = []
if dolphin_sysprompt_mode == "Japanese to Danbooru Dictionary" and is_japanese(raw_prompt):
prompts = list_uniq(jatags_to_danbooru_tags(to_list_ja(raw_prompt)) + ["nsfw", "explicit"])
else:
prompts = list_uniq(to_list(raw_prompt) + ["nsfw", "explicit"])
return ", ".join(prompts), gr.update(interactive=True), gr.update(interactive=True)
except Exception as e:
print(e)
return "", gr.update(), gr.update()
@torch.inference_mode()
@spaces.GPU(duration=59)
def dolphin_respond_auto(
message: str,
history: list[tuple[str, str]],
model: str = default_llm_model_filename,
system_message: str = get_dolphin_sysprompt(),
max_tokens: int = 1024,
temperature: float = 0.7,
top_p: float = 0.95,
top_k: int = 40,
repeat_penalty: float = 1.1,
lora: str = "",
lora_scale: float = 1.0,
state: dict = {},
progress=gr.Progress(track_tqdm=True),
):
try:
model_path = Path(f"{llm_models_dir}/{model}")
#if not is_japanese(message): return [(None, None)]
progress(0, desc="Processing...")
override_llm_format = get_state(state, "override_llm_format")
if override_llm_format: chat_template = override_llm_format
else: chat_template = llm_models[model][1]
kwargs = {}
if lora:
kwargs["lora_path"] = str(Path(f"{llm_loras_dir}/{lora}"))
kwargs["lora_scale"] = lora_scale
else:
kwargs["flash_attn"] = True
llm = Llama(
model_path=str(model_path),
n_gpu_layers=81, # 81
n_batch=1024,
n_ctx=8192, #8192
**kwargs,
)
provider = LlamaCppPythonProvider(llm)
agent = LlamaCppAgent(
provider,
system_prompt=f"{system_message}",
predefined_messages_formatter_type=chat_template if not isinstance(chat_template, MessagesFormatter) else None,
custom_messages_formatter=chat_template if isinstance(chat_template, MessagesFormatter) else None,
debug_output=False
)
settings = provider.get_provider_default_settings()
settings.temperature = temperature
settings.top_k = top_k
settings.top_p = top_p
settings.max_tokens = max_tokens
settings.repeat_penalty = repeat_penalty
settings.stream = True
messages = BasicChatHistory()
for msn in history:
user = {
'role': Roles.user,
'content': msn[0]
}
assistant = {
'role': Roles.assistant,
'content': msn[1]
}
messages.add_message(user)
messages.add_message(assistant)
progress(0, desc="Translating...")
stream = agent.get_chat_response(
message,
llm_sampling_settings=settings,
chat_history=messages,
returns_streaming_generator=True,
print_output=False
)
progress(0.5, desc="Processing...")
outputs = ""
for output in stream:
outputs += output
yield [(outputs, None)], gr.update(), gr.update()
except Exception as e:
print(e)
yield [("", None)], gr.update(), gr.update()
finally:
torch.cuda.empty_cache()
gc.collect()
def dolphin_parse_simple(
message: str,
history: list[tuple[str, str]],
state: dict,
):
try:
#if not is_japanese(message): return message
dolphin_sysprompt_mode = get_state(state, "dolphin_sysprompt_mode")
if dolphin_sysprompt_mode == "Chat with LLM" or not history or len(history) < 1: return message
msg = history[-1][0]
raw_prompt = get_raw_prompt(msg)
prompts = []
if dolphin_sysprompt_mode == "Japanese to Danbooru Dictionary" and is_japanese(raw_prompt):
prompts = list_uniq(jatags_to_danbooru_tags(to_list_ja(raw_prompt)) + ["nsfw", "explicit", "rating_explicit"])
else:
prompts = list_uniq(to_list(raw_prompt) + ["nsfw", "explicit", "rating_explicit"])
return ", ".join(prompts)
except Exception as e:
print(e)
return ""
# https://huggingface.co/spaces/CaioXapelaum/GGUF-Playground
import cv2
cv2.setNumThreads(1)
@torch.inference_mode()
@spaces.GPU(duration=59)
def respond_playground(
message: str,
history: list[tuple[str, str]],
model: str = default_llm_model_filename,
system_message: str = get_dolphin_sysprompt(),
max_tokens: int = 1024,
temperature: float = 0.7,
top_p: float = 0.95,
top_k: int = 40,
repeat_penalty: float = 1.1,
lora: str = "",
lora_scale: float = 1.0,
state: dict = {},
progress=gr.Progress(track_tqdm=True),
):
try:
model_path = Path(f"{llm_models_dir}/{model}")
if not model_path.exists(): raise gr.Error(f"Model file not found: {str(model_path)}")
override_llm_format = get_state(state, "override_llm_format")
if override_llm_format: chat_template = override_llm_format
else: chat_template = llm_models[model][1]
kwargs = {}
if lora:
kwargs["lora_path"] = str(Path(f"{llm_loras_dir}/{lora}"))
kwargs["lora_scale"] = lora_scale
else:
kwargs["flash_attn"] = True
llm = Llama(
model_path=str(model_path),
n_gpu_layers=81, # 81
n_batch=1024,
n_ctx=8192, #8192
**kwargs,
)
provider = LlamaCppPythonProvider(llm)
agent = LlamaCppAgent(
provider,
system_prompt=f"{system_message}",
predefined_messages_formatter_type=chat_template if not isinstance(chat_template, MessagesFormatter) else None,
custom_messages_formatter=chat_template if isinstance(chat_template, MessagesFormatter) else None,
debug_output=False
)
settings = provider.get_provider_default_settings()
settings.temperature = temperature
settings.top_k = top_k
settings.top_p = top_p
settings.max_tokens = max_tokens
settings.repeat_penalty = repeat_penalty
settings.stream = True
messages = BasicChatHistory()
# Add user and assistant messages to the history
for msn in history:
user = {'role': Roles.user, 'content': msn[0]}
assistant = {'role': Roles.assistant, 'content': msn[1]}
messages.add_message(user)
messages.add_message(assistant)
# Stream the response
stream = agent.get_chat_response(
message,
llm_sampling_settings=settings,
chat_history=messages,
returns_streaming_generator=True,
print_output=False
)
outputs = ""
for output in stream:
outputs += output
yield outputs
except Exception as e:
print(e)
raise gr.Error(f"Error: {e}")
#yield ""
finally:
torch.cuda.empty_cache()
gc.collect()
|