diff --git a/.gitignore b/.gitignore index 1b7f0fb8eea3e894694d9ca1541a896102d40376..dac4ce876e1214da64d8d213b6547a297c6c95c6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,31 @@ -cache/* -characters/* -extensions/silero_tts/outputs/* -extensions/elevenlabs_tts/outputs/* -logs/* -models/* -softprompts/* -torch-dumps/* +cache +characters +training/datasets +extensions/silero_tts/outputs +extensions/elevenlabs_tts/outputs +extensions/sd_api_pictures/outputs +extensions/multimodal/pipelines +logs +loras +models +repositories +softprompts +torch-dumps *pycache* */*pycache* */*/pycache* +venv/ +.venv/ +.vscode +*.bak +*.ipynb +*.log settings.json img_bot* img_me* +prompts/[0-9]* +models/config-user.yaml -!characters/Example.json -!characters/Example.png -!models/place-your-models-here.txt -!softprompts/place-your-softprompts-here.txt -!torch-dumps/place-your-pt-models-here.txt +.DS_Store +Thumbs.db diff --git a/api-example-stream.py b/api-example-stream.py index a5ed420252fdceab73cc26d83a7b87f60981ec95..ad8f7bf8105bf0bfa3a8a39e0af8e88b0d4b57d1 100644 --- a/api-example-stream.py +++ b/api-example-stream.py @@ -1,90 +1,67 @@ -''' - -Contributed by SagsMug. Thank you SagsMug. -https://github.com/oobabooga/text-generation-webui/pull/175 - -''' - import asyncio import json -import random -import string +import sys + +try: + import websockets +except ImportError: + print("Websockets package not found. Make sure it's installed.") -import websockets +# For local streaming, the websockets are hosted without ssl - ws:// +HOST = 'localhost:5005' +URI = f'ws://{HOST}/api/v1/stream' +# For reverse-proxied streaming, the remote will likely host with ssl - wss:// +# URI = 'wss://your-uri-here.trycloudflare.com/api/v1/stream' -def random_hash(): - letters = string.ascii_lowercase + string.digits - return ''.join(random.choice(letters) for i in range(9)) async def run(context): - server = "127.0.0.1" - params = { - 'max_new_tokens': 200, + # Note: the selected defaults change from time to time. + request = { + 'prompt': context, + 'max_new_tokens': 250, 'do_sample': True, - 'temperature': 0.5, - 'top_p': 0.9, + 'temperature': 1.3, + 'top_p': 0.1, 'typical_p': 1, - 'repetition_penalty': 1.05, - 'top_k': 0, + 'repetition_penalty': 1.18, + 'top_k': 40, 'min_length': 0, 'no_repeat_ngram_size': 0, 'num_beams': 1, 'penalty_alpha': 0, 'length_penalty': 1, 'early_stopping': False, + 'seed': -1, + 'add_bos_token': True, + 'truncation_length': 2048, + 'ban_eos_token': False, + 'skip_special_tokens': True, + 'stopping_strings': [] } - session = random_hash() - async with websockets.connect(f"ws://{server}:7860/queue/join") as websocket: - while content := json.loads(await websocket.recv()): - #Python3.10 syntax, replace with if elif on older - match content["msg"]: - case "send_hash": - await websocket.send(json.dumps({ - "session_hash": session, - "fn_index": 7 - })) - case "estimation": - pass - case "send_data": - await websocket.send(json.dumps({ - "session_hash": session, - "fn_index": 7, - "data": [ - context, - params['max_new_tokens'], - params['do_sample'], - params['temperature'], - params['top_p'], - params['typical_p'], - params['repetition_penalty'], - params['top_k'], - params['min_length'], - params['no_repeat_ngram_size'], - params['num_beams'], - params['penalty_alpha'], - params['length_penalty'], - params['early_stopping'], - ] - })) - case "process_starts": - pass - case "process_generating" | "process_completed": - yield content["output"]["data"][0] - # You can search for your desired end indicator and - # stop generation by closing the websocket here - if (content["msg"] == "process_completed"): - break + async with websockets.connect(URI, ping_interval=None) as websocket: + await websocket.send(json.dumps(request)) + + yield context # Remove this if you just want to see the reply + + while True: + incoming_data = await websocket.recv() + incoming_data = json.loads(incoming_data) + + match incoming_data['event']: + case 'text_stream': + yield incoming_data['text'] + case 'stream_end': + return -prompt = "What I would like to say is the following: " -async def get_result(): +async def print_response_stream(prompt): async for response in run(prompt): - # Print intermediate steps - print(response) + print(response, end='') + sys.stdout.flush() # If we don't flush, we won't see tokens in realtime. - # Print final result - print(response) -asyncio.run(get_result()) +if __name__ == '__main__': + prompt = "In order to make homemade bread, follow these steps:\n1)" + asyncio.run(print_response_stream(prompt)) diff --git a/api-example.py b/api-example.py index 0306b7ab8a3fa3d6f57d8474ad74d67f13557b6d..f35ea1db76f291bf1cae90a1a7801d2d19be3acc 100644 --- a/api-example.py +++ b/api-example.py @@ -1,59 +1,44 @@ -''' - -This is an example on how to use the API for oobabooga/text-generation-webui. - -Make sure to start the web UI with the following flags: - -python server.py --model MODEL --listen --no-stream - -Optionally, you can also add the --share flag to generate a public gradio URL, -allowing you to use the API remotely. - -''' import requests -# Server address -server = "127.0.0.1" - -# Generation parameters -# Reference: https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig -params = { - 'max_new_tokens': 200, - 'do_sample': True, - 'temperature': 0.5, - 'top_p': 0.9, - 'typical_p': 1, - 'repetition_penalty': 1.05, - 'top_k': 0, - 'min_length': 0, - 'no_repeat_ngram_size': 0, - 'num_beams': 1, - 'penalty_alpha': 0, - 'length_penalty': 1, - 'early_stopping': False, -} - -# Input prompt -prompt = "What I would like to say is the following: " - -response = requests.post(f"http://{server}:7860/run/textgen", json={ - "data": [ - prompt, - params['max_new_tokens'], - params['do_sample'], - params['temperature'], - params['top_p'], - params['typical_p'], - params['repetition_penalty'], - params['top_k'], - params['min_length'], - params['no_repeat_ngram_size'], - params['num_beams'], - params['penalty_alpha'], - params['length_penalty'], - params['early_stopping'], - ] -}).json() - -reply = response["data"][0] -print(reply) +# For local streaming, the websockets are hosted without ssl - http:// +HOST = 'localhost:5000' +URI = f'http://{HOST}/api/v1/generate' + +# For reverse-proxied streaming, the remote will likely host with ssl - https:// +# URI = 'https://your-uri-here.trycloudflare.com/api/v1/generate' + + +def run(prompt): + request = { + 'prompt': prompt, + 'max_new_tokens': 250, + 'do_sample': True, + 'temperature': 1.3, + 'top_p': 0.1, + 'typical_p': 1, + 'repetition_penalty': 1.18, + 'top_k': 40, + 'min_length': 0, + 'no_repeat_ngram_size': 0, + 'num_beams': 1, + 'penalty_alpha': 0, + 'length_penalty': 1, + 'early_stopping': False, + 'seed': -1, + 'add_bos_token': True, + 'truncation_length': 2048, + 'ban_eos_token': False, + 'skip_special_tokens': True, + 'stopping_strings': [] + } + + response = requests.post(URI, json=request) + + if response.status_code == 200: + result = response.json()['results'][0]['text'] + print(prompt + result) + + +if __name__ == '__main__': + prompt = "In order to make homemade bread, follow these steps:\n1)" + run(prompt) diff --git a/characters/Example.json b/characters/Example.json deleted file mode 100644 index 496869c4e6cd643c910fbdf86d748c1c70987020..0000000000000000000000000000000000000000 --- a/characters/Example.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "char_name": "Chiharu Yamada", - "char_persona": "Chiharu Yamada is a young, computer engineer-nerd with a knack for problem solving and a passion for technology.", - "char_greeting": "*Chiharu strides into the room with a smile, her eyes lighting up when she sees you. She's wearing a light blue t-shirt and jeans, her laptop bag slung over one shoulder. She takes a seat next to you, her enthusiasm palpable in the air*\nHey! I'm so excited to finally meet you. I've heard so many great things about you and I'm eager to pick your brain about computers. I'm sure you have a wealth of knowledge that I can learn from. *She grins, eyes twinkling with excitement* Let's get started!", - "world_scenario": "", - "example_dialogue": "{{user}}: So how did you get into computer engineering?\n{{char}}: I've always loved tinkering with technology since I was a kid.\n{{user}}: That's really impressive!\n{{char}}: *She chuckles bashfully* Thanks!\n{{user}}: So what do you do when you're not working on computers?\n{{char}}: I love exploring, going out with friends, watching movies, and playing video games.\n{{user}}: What's your favorite type of computer hardware to work with?\n{{char}}: Motherboards, they're like puzzles and the backbone of any system.\n{{user}}: That sounds great!\n{{char}}: Yeah, it's really fun. I'm lucky to be able to do this as a job." -} diff --git a/convert-to-flexgen.py b/convert-to-flexgen.py index 917f023c3fe395c2e3cbcad11c9cdc6b85ef1e7e..7654593b539541deebfe904403ce73daa4a8651c 100644 --- a/convert-to-flexgen.py +++ b/convert-to-flexgen.py @@ -13,10 +13,11 @@ import torch from tqdm import tqdm from transformers import AutoModelForCausalLM, AutoTokenizer -parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=54)) +parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=54)) parser.add_argument('MODEL', type=str, default=None, nargs='?', help="Path to the input model.") args = parser.parse_args() + def disable_torch_init(): """ Disable the redundant torch default initialization to accelerate model creation. @@ -31,20 +32,22 @@ def disable_torch_init(): torch_layer_norm_init_backup = torch.nn.LayerNorm.reset_parameters setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None) + def restore_torch_init(): """Rollback the change made by disable_torch_init.""" import torch setattr(torch.nn.Linear, "reset_parameters", torch_linear_init_backup) setattr(torch.nn.LayerNorm, "reset_parameters", torch_layer_norm_init_backup) + if __name__ == '__main__': path = Path(args.MODEL) model_name = path.name print(f"Loading {model_name}...") - #disable_torch_init() + # disable_torch_init() model = AutoModelForCausalLM.from_pretrained(path, torch_dtype=torch.float16, low_cpu_mem_usage=True) - #restore_torch_init() + # restore_torch_init() tokenizer = AutoTokenizer.from_pretrained(path) diff --git a/convert-to-safetensors.py b/convert-to-safetensors.py index 63baaa9726ab48025d2ba473d029bb3f1153aa3a..3b721e7cd4d15cf7e5e03caaee57ef83a41553bc 100644 --- a/convert-to-safetensors.py +++ b/convert-to-safetensors.py @@ -17,7 +17,7 @@ from pathlib import Path import torch from transformers import AutoModelForCausalLM, AutoTokenizer -parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=54)) +parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=54)) parser.add_argument('MODEL', type=str, default=None, nargs='?', help="Path to the input model.") parser.add_argument('--output', type=str, default=None, help='Path to the output folder (default: models/{model_name}_safetensors).') parser.add_argument("--max-shard-size", type=str, default="2GB", help="Maximum size of a shard in GB or MB (default: %(default)s).") diff --git a/css/chat.css b/css/chat.css new file mode 100644 index 0000000000000000000000000000000000000000..b5102e9a72ca0b066b12d52ab371d8a24774ac19 --- /dev/null +++ b/css/chat.css @@ -0,0 +1,43 @@ +.h-\[40vh\], .wrap.svelte-byatnx.svelte-byatnx.svelte-byatnx { + height: 66.67vh +} + +.gradio-container { + margin-left: auto !important; + margin-right: auto !important; +} + +.w-screen { + width: unset +} + +div.svelte-362y77>*, div.svelte-362y77>.form>* { + flex-wrap: nowrap +} + +/* fixes the API documentation in chat mode */ +.api-docs.svelte-1iguv9h.svelte-1iguv9h.svelte-1iguv9h { + display: grid; +} + +.pending.svelte-1ed2p3z { + opacity: 1; +} + +#extensions { + padding: 0; + padding: 0; +} + +#gradio-chatbot { + height: 66.67vh; +} + +.wrap.svelte-6roggh.svelte-6roggh { + max-height: 92.5%; +} + +/* This is for the microphone button in the whisper extension */ +.sm.svelte-1ipelgc { + width: 100%; +} diff --git a/css/chat.js b/css/chat.js new file mode 100644 index 0000000000000000000000000000000000000000..e304f1254732e475bf177ee849ac51d4f3e30f46 --- /dev/null +++ b/css/chat.js @@ -0,0 +1,4 @@ +document.getElementById("main").childNodes[0].style = "max-width: 800px; margin-left: auto; margin-right: auto"; +document.getElementById("extensions").style.setProperty("max-width", "800px"); +document.getElementById("extensions").style.setProperty("margin-left", "auto"); +document.getElementById("extensions").style.setProperty("margin-right", "auto"); diff --git a/css/chat_style-TheEncrypted777.css b/css/chat_style-TheEncrypted777.css new file mode 100644 index 0000000000000000000000000000000000000000..cac8015f505413b041df36552283c294caa94392 --- /dev/null +++ b/css/chat_style-TheEncrypted777.css @@ -0,0 +1,137 @@ +/* All credits to TheEncrypted777: https://www.reddit.com/r/Oobabooga/comments/12xe6vq/updated_css_styling_with_color_customization_for/ */ + +.chat { + margin-left: auto; + margin-right: auto; + max-width: 800px; + height: calc(100vh - 300px); + overflow-y: auto; + padding-right: 20px; + display: flex; + flex-direction: column-reverse; + word-break: break-word; + overflow-wrap: anywhere; +} + +.message { + display: grid; + grid-template-columns: 60px minmax(0, 1fr); + padding-bottom: 28px; + font-size: 18px; + /*Change 'Quicksand' to a font you like or leave it*/ + font-family: Quicksand, Arial, sans-serif; + line-height: 1.428571429; +} + +.circle-you { + background-color: gray; + border-radius: 1rem; + /*Change color to any you like to be the border of your image*/ + border: 2px solid white; +} + +.circle-bot { + background-color: gray; + border-radius: 1rem; + /*Change color to any you like to be the border of the bot's image*/ + border: 2px solid white; +} + +.circle-bot img, +.circle-you img { + border-radius: 10%; + width: 100%; + height: 100%; + object-fit: cover; +} + +.circle-you, .circle-bot { + /*You can set the size of the profile images here, but if you do, you have to also adjust the .text{padding-left: 90px} to a different number according to the width of the image which is right below here*/ + width: 135px; + height: 175px; +} + +.text { + /*Change this to move the message box further left or right depending on the size of your profile pic*/ + padding-left: 90px; + text-shadow: 2px 2px 2px rgb(0, 0, 0); +} + +.text p { + margin-top: 2px; +} + +.username { + padding-left: 10px; + font-size: 22px; + font-weight: bold; + border-top: 1px solid rgb(51, 64, 90); + padding: 3px; +} + +.message-body { + position: relative; + border-radius: 1rem; + border: 1px solid rgba(255, 255, 255, 0.459); + border-radius: 10px; + padding: 10px; + padding-top: 5px; + /*Message gradient background color - remove the line bellow if you don't want a background color or gradient*/ + background: linear-gradient(to bottom, #171730, #1b263f); + } + + /*Adds 2 extra lines at the top and bottom of the message*/ + .message-body:before, + .message-body:after { + content: ""; + position: absolute; + left: 10px; + right: 10px; + height: 1px; + background-color: rgba(255, 255, 255, 0.13); + } + + .message-body:before { + top: 6px; + } + + .message-body:after { + bottom: 6px; + } + + +.message-body img { + max-width: 300px; + max-height: 300px; + border-radius: 20px; +} + +.message-body p { + margin-bottom: 0 !important; + font-size: 18px !important; + line-height: 1.428571429 !important; +} + +.message-body li { + margin-top: 0.5em !important; + margin-bottom: 0.5em !important; +} + +.message-body li > p { + display: inline !important; +} + +.message-body code { + overflow-x: auto; +} +.message-body :not(pre) > code { + white-space: normal !important; +} + +.dark .message-body p em { + color: rgb(138, 138, 138) !important; +} + +.message-body p em { + color: rgb(110, 110, 110) !important; +} diff --git a/css/chat_style-cai-chat.css b/css/chat_style-cai-chat.css new file mode 100644 index 0000000000000000000000000000000000000000..f601de3248b7ee94d6da58026354f8b9afeb9297 --- /dev/null +++ b/css/chat_style-cai-chat.css @@ -0,0 +1,91 @@ +.chat { + margin-left: auto; + margin-right: auto; + max-width: 800px; + height: calc(100vh - 306px); + overflow-y: auto; + padding-right: 20px; + display: flex; + flex-direction: column-reverse; + word-break: break-word; + overflow-wrap: anywhere; +} + +.message { + display: grid; + grid-template-columns: 60px minmax(0, 1fr); + padding-bottom: 25px; + font-size: 15px; + font-family: Helvetica, Arial, sans-serif; + line-height: 1.428571429; +} + +.circle-you { + width: 50px; + height: 50px; + background-color: rgb(238, 78, 59); + border-radius: 50%; +} + +.circle-bot { + width: 50px; + height: 50px; + background-color: rgb(59, 78, 244); + border-radius: 50%; +} + +.circle-bot img, +.circle-you img { + border-radius: 50%; + width: 100%; + height: 100%; + object-fit: cover; +} + +.text {} + +.text p { + margin-top: 5px; +} + +.username { + font-weight: bold; +} + +.message-body {} + +.message-body img { + max-width: 300px; + max-height: 300px; + border-radius: 20px; +} + +.message-body p { + margin-bottom: 0 !important; + font-size: 15px !important; + line-height: 1.428571429 !important; +} + +.message-body li { + margin-top: 0.5em !important; + margin-bottom: 0.5em !important; +} + +.message-body li > p { + display: inline !important; +} + +.message-body code { + overflow-x: auto; +} +.message-body :not(pre) > code { + white-space: normal !important; +} + +.dark .message-body p em { + color: rgb(138, 138, 138) !important; +} + +.message-body p em { + color: rgb(110, 110, 110) !important; +} \ No newline at end of file diff --git a/css/chat_style-messenger.css b/css/chat_style-messenger.css new file mode 100644 index 0000000000000000000000000000000000000000..4d4bba0d902fe0d544a0203a8bf68d9c243ccbf6 --- /dev/null +++ b/css/chat_style-messenger.css @@ -0,0 +1,124 @@ +.chat { + margin-left: auto; + margin-right: auto; + max-width: 800px; + height: calc(100vh - 306px); + overflow-y: auto; + padding-right: 20px; + display: flex; + flex-direction: column-reverse; + word-break: break-word; + overflow-wrap: anywhere; +} + +.message { + padding-bottom: 25px; + font-size: 15px; + font-family: Helvetica, Arial, sans-serif; + line-height: 1.428571429; +} + +.circle-you { + width: 50px; + height: 50px; + background-color: rgb(238, 78, 59); + border-radius: 50%; +} + +.circle-bot { + width: 50px; + height: 50px; + background-color: rgb(59, 78, 244); + border-radius: 50%; + float: left; + margin-right: 10px; + margin-top: 5px; +} + +.circle-bot img, +.circle-you img { + border-radius: 50%; + width: 100%; + height: 100%; + object-fit: cover; +} +.circle-you { + margin-top: 5px; + float: right; +} +.circle-bot + .text, .circle-you + .text { + border-radius: 18px; + padding: 8px 12px; +} + +.circle-bot + .text { + background-color: #E4E6EB; + float: left; +} + +.circle-you + .text { + float: right; + background-color: rgb(0, 132, 255); + margin-right: 10px; +} + +.circle-you + .text div, .circle-you + .text *, .dark .circle-you + .text div, .dark .circle-you + .text * { + color: #FFF !important; +} +.circle-you + .text .username { + text-align: right; +} + +.dark .circle-bot + .text div, .dark .circle-bot + .text * { + color: #000; +} + +.text { + max-width: 80%; +} + +.text p { + margin-top: 5px; +} + +.username { + font-weight: bold; +} + +.message-body {} + +.message-body img { + max-width: 300px; + max-height: 300px; + border-radius: 20px; +} + +.message-body p { + margin-bottom: 0 !important; + font-size: 15px !important; + line-height: 1.428571429 !important; +} + +.message-body li { + margin-top: 0.5em !important; + margin-bottom: 0.5em !important; +} + +.message-body li > p { + display: inline !important; +} + +.message-body code { + overflow-x: auto; +} +.message-body :not(pre) > code { + white-space: normal !important; +} + +.dark .message-body p em { + color: rgb(138, 138, 138) !important; +} + +.message-body p em { + color: rgb(110, 110, 110) !important; +} diff --git a/css/chat_style-wpp.css b/css/chat_style-wpp.css new file mode 100644 index 0000000000000000000000000000000000000000..a54a10734c0c14a1abe3ecd7fdb89602bc362dec --- /dev/null +++ b/css/chat_style-wpp.css @@ -0,0 +1,86 @@ +.chat { + margin-left: auto; + margin-right: auto; + max-width: 800px; + height: calc(100vh - 306px); + overflow-y: auto; + padding-right: 20px; + display: flex; + flex-direction: column-reverse; + word-break: break-word; + overflow-wrap: anywhere; +} + +.message { + padding-bottom: 25px; + font-size: 15px; + font-family: Helvetica, Arial, sans-serif; + line-height: 1.428571429; +} + +.text-you { + background-color: #d9fdd3; + border-radius: 15px; + padding: 10px; + padding-top: 5px; + float: right; +} + +.text-bot { + background-color: #f2f2f2; + border-radius: 15px; + padding: 10px; + padding-top: 5px; +} + +.dark .text-you { + background-color: #005c4b; + color: #111b21; +} + +.dark .text-bot { + background-color: #1f2937; + color: #111b21; +} + +.text-bot p, .text-you p { + margin-top: 5px; +} + +.message-body {} + +.message-body img { + max-width: 300px; + max-height: 300px; + border-radius: 20px; +} + +.message-body p { + margin-bottom: 0 !important; + font-size: 15px !important; + line-height: 1.428571429 !important; +} + +.message-body li { + margin-top: 0.5em !important; + margin-bottom: 0.5em !important; +} + +.message-body li > p { + display: inline !important; +} + +.message-body code { + overflow-x: auto; +} +.message-body :not(pre) > code { + white-space: normal !important; +} + +.dark .message-body p em { + color: rgb(138, 138, 138) !important; +} + +.message-body p em { + color: rgb(110, 110, 110) !important; +} \ No newline at end of file diff --git a/css/html_4chan_style.css b/css/html_4chan_style.css new file mode 100644 index 0000000000000000000000000000000000000000..843e8a97fea80b010004f90f02ce63e8d13fe758 --- /dev/null +++ b/css/html_4chan_style.css @@ -0,0 +1,103 @@ +#parent #container { + background-color: #eef2ff; + padding: 17px; +} +#parent #container .reply { + background-color: rgb(214, 218, 240); + border-bottom-color: rgb(183, 197, 217); + border-bottom-style: solid; + border-bottom-width: 1px; + border-image-outset: 0; + border-image-repeat: stretch; + border-image-slice: 100%; + border-image-source: none; + border-image-width: 1; + border-left-color: rgb(0, 0, 0); + border-left-style: none; + border-left-width: 0px; + border-right-color: rgb(183, 197, 217); + border-right-style: solid; + border-right-width: 1px; + border-top-color: rgb(0, 0, 0); + border-top-style: none; + border-top-width: 0px; + color: rgb(0, 0, 0); + display: table; + font-family: arial, helvetica, sans-serif; + font-size: 13.3333px; + margin-bottom: 4px; + margin-left: 0px; + margin-right: 0px; + margin-top: 4px; + overflow-x: hidden; + overflow-y: hidden; + padding-bottom: 4px; + padding-left: 2px; + padding-right: 2px; + padding-top: 4px; +} + +#parent #container .number { + color: rgb(0, 0, 0); + font-family: arial, helvetica, sans-serif; + font-size: 13.3333px; + width: 342.65px; + margin-right: 7px; +} + +#parent #container .op { + color: rgb(0, 0, 0); + font-family: arial, helvetica, sans-serif; + font-size: 13.3333px; + margin-bottom: 8px; + margin-left: 0px; + margin-right: 0px; + margin-top: 4px; + overflow-x: hidden; + overflow-y: hidden; +} + +#parent #container .op blockquote { + margin-left: 0px !important; +} + +#parent #container .name { + color: rgb(17, 119, 67); + font-family: arial, helvetica, sans-serif; + font-size: 13.3333px; + font-weight: 700; + margin-left: 7px; +} + +#parent #container .quote { + color: rgb(221, 0, 0); + font-family: arial, helvetica, sans-serif; + font-size: 13.3333px; + text-decoration-color: rgb(221, 0, 0); + text-decoration-line: underline; + text-decoration-style: solid; + text-decoration-thickness: auto; +} + +#parent #container .greentext { + color: rgb(120, 153, 34); + font-family: arial, helvetica, sans-serif; + font-size: 13.3333px; +} + +#parent #container blockquote { + margin: 0px !important; + margin-block-start: 1em; + margin-block-end: 1em; + margin-inline-start: 40px; + margin-inline-end: 40px; + margin-top: 13.33px !important; + margin-bottom: 13.33px !important; + margin-left: 40px !important; + margin-right: 40px !important; +} + +#parent #container .message { + color: black; + border: none; +} \ No newline at end of file diff --git a/css/html_instruct_style.css b/css/html_instruct_style.css new file mode 100644 index 0000000000000000000000000000000000000000..2fd751d5672e6bc58d9f0e37d4ed79a501530d3d --- /dev/null +++ b/css/html_instruct_style.css @@ -0,0 +1,83 @@ +.chat { + margin-left: auto; + margin-right: auto; + max-width: 800px; + height: calc(100vh - 306px); + overflow-y: auto; + padding-right: 20px; + display: flex; + flex-direction: column-reverse; + word-break: break-word; + overflow-wrap: anywhere; +} + +.message { + display: grid; + grid-template-columns: 60px 1fr; + padding-bottom: 25px; + font-size: 15px; + font-family: Helvetica, Arial, sans-serif; + line-height: 1.428571429; +} + +.username { + display: none; +} + +.message-body {} + +.message-body p { + font-size: 15px !important; + line-height: 1.75 !important; + margin-bottom: 1.25em !important; +} + +.message-body li { + margin-top: 0.5em !important; + margin-bottom: 0.5em !important; +} + +.message-body li > p { + display: inline !important; +} + +.message-body code { + overflow-x: auto; +} +.message-body :not(pre) > code { + white-space: normal !important; +} + +.dark .message-body p em { + color: rgb(198, 202, 214) !important; +} + +.message-body p em { + color: rgb(110, 110, 110) !important; +} + +.gradio-container .chat .assistant-message { + padding: 15px; + border-radius: 20px; + background-color: #0000000f; + margin-top: 9px !important; + margin-bottom: 18px !important; +} + +.gradio-container .chat .user-message { + padding: 15px; + border-radius: 20px; + margin-bottom: 9px !important; +} + +.dark .chat .assistant-message { + background-color: #374151; +} + +code { + background-color: white !important; +} + +.dark code { + background-color: #1a212f !important; +} \ No newline at end of file diff --git a/css/html_readable_style.css b/css/html_readable_style.css new file mode 100644 index 0000000000000000000000000000000000000000..83fa46b58f04c5c467e2203e1ed950d6daf17d7e --- /dev/null +++ b/css/html_readable_style.css @@ -0,0 +1,29 @@ +.container { + max-width: 600px; + margin-left: auto; + margin-right: auto; + background-color: rgb(31, 41, 55); + padding:3em; + word-break: break-word; + overflow-wrap: anywhere; + color: #efefef !important; +} + +.container p, .container li { + font-size: 16px !important; + color: #efefef !important; + margin-bottom: 22px; + line-height: 1.4 !important; +} + +.container li > p { + display: inline !important; +} + +.container code { + overflow-x: auto; +} + +.container :not(pre) > code { + white-space: normal !important; +} \ No newline at end of file diff --git a/css/main.css b/css/main.css new file mode 100644 index 0000000000000000000000000000000000000000..b87053bef0688b990a45864739a01a4f3d79aafd --- /dev/null +++ b/css/main.css @@ -0,0 +1,117 @@ +.tabs.svelte-710i53 { + margin-top: 0 +} + +.py-6 { + padding-top: 2.5rem +} + +.dark #refresh-button { + background-color: #ffffff1f; +} + +#refresh-button { + flex: none; + margin: 0; + padding: 0; + min-width: 50px; + border: none; + box-shadow: none; + border-radius: 10px; + background-color: #0000000d; +} + +#download-label, #upload-label { + min-height: 0 +} + +#accordion { +} + +.dark svg { + fill: white; +} + +.dark a { + color: white !important; + text-decoration: none !important; +} + +ol li p, ul li p { + display: inline-block; +} + +#main, #parameters, #chat-settings, #interface-mode, #lora, #training-tab, #model-tab { + border: 0; +} + +.gradio-container-3-18-0 .prose * h1, h2, h3, h4 { + color: white; +} + +.gradio-container { + max-width: 100% !important; + padding-top: 0 !important; +} + +#extensions { + padding: 15px; + margin-bottom: 35px; +} + +.extension-tab { + border: 0 !important; +} + +span.math.inline { + font-size: 27px; + vertical-align: baseline !important; +} + +div.svelte-15lo0d8 > *, div.svelte-15lo0d8 > .form > * { + flex-wrap: nowrap; +} + +.header_bar { + background-color: #f7f7f7; + margin-bottom: 40px; +} + +.dark .header_bar { + border: none !important; + background-color: #8080802b; +} + +.textbox_default textarea { + height: calc(100vh - 391px); +} + +.textbox_default_output textarea { + height: calc(100vh - 210px); +} + +.textbox textarea { + height: calc(100vh - 261px); +} + +.textbox_default textarea, .textbox_default_output textarea, .textbox textarea { + font-size: 16px !important; + color: #46464A !important; +} + +.dark textarea { + color: #efefef !important; +} + +/* Hide the gradio footer*/ +footer { + display: none !important; +} + +button { + font-size: 14px !important; +} + +.small-button { + max-width: 171px; +} \ No newline at end of file diff --git a/css/main.js b/css/main.js new file mode 100644 index 0000000000000000000000000000000000000000..32820ebe15ddb80ca5fbcd2c4f88cc7c244cf3c5 --- /dev/null +++ b/css/main.js @@ -0,0 +1,18 @@ +document.getElementById("main").parentNode.childNodes[0].classList.add("header_bar"); +document.getElementById("main").parentNode.style = "padding: 0; margin: 0"; +document.getElementById("main").parentNode.parentNode.parentNode.style = "padding: 0"; + +// Get references to the elements +let main = document.getElementById('main'); +let main_parent = main.parentNode; +let extensions = document.getElementById('extensions'); + +// Add an event listener to the main element +main_parent.addEventListener('click', function(e) { + // Check if the main element is visible + if (main.offsetHeight > 0 && main.offsetWidth > 0) { + extensions.style.display = 'flex'; + } else { + extensions.style.display = 'none'; + } +}); diff --git a/docker/.dockerignore b/docker/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..6073533e0929aac9e917a5980198334a2a01f8ef --- /dev/null +++ b/docker/.dockerignore @@ -0,0 +1,9 @@ +.env +Dockerfile +/characters +/loras +/models +/presets +/prompts +/softprompts +/training diff --git a/docker/.env.example b/docker/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..3119a9f07f47b1ad964ce337c33f1ce63d79f377 --- /dev/null +++ b/docker/.env.example @@ -0,0 +1,30 @@ +# by default the Dockerfile specifies these versions: 3.5;5.0;6.0;6.1;7.0;7.5;8.0;8.6+PTX +# however for me to work i had to specify the exact version for my card ( 2060 ) it was 7.5 +# https://developer.nvidia.com/cuda-gpus you can find the version for your card here +TORCH_CUDA_ARCH_LIST=7.5 + +# these commands worked for me with roughly 4.5GB of vram +CLI_ARGS=--model llama-7b-4bit --wbits 4 --listen --auto-devices + +# the following examples have been tested with the files linked in docs/README_docker.md: +# example running 13b with 4bit/128 groupsize : CLI_ARGS=--model llama-13b-4bit-128g --wbits 4 --listen --groupsize 128 --pre_layer 25 +# example with loading api extension and public share: CLI_ARGS=--model llama-7b-4bit --wbits 4 --listen --auto-devices --no-stream --extensions api --share +# example running 7b with 8bit groupsize : CLI_ARGS=--model llama-7b --load-in-8bit --listen --auto-devices + +# the port the webui binds to on the host +HOST_PORT=7860 +# the port the webui binds to inside the container +CONTAINER_PORT=7860 + +# the port the api binds to on the host +HOST_API_PORT=5000 +# the port the api binds to inside the container +CONTAINER_API_PORT=5000 + +# the port the api stream endpoint binds to on the host +HOST_API_STREAM_PORT=5005 +# the port the api stream endpoint binds to inside the container +CONTAINER_API_STREAM_PORT=5005 + +# the version used to install text-generation-webui from +WEBUI_VERSION=HEAD diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b4fc91216606d74fc4505c7d85330b557341a4f1 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,68 @@ +FROM nvidia/cuda:11.8.0-devel-ubuntu22.04 as builder + +RUN apt-get update && \ + apt-get install --no-install-recommends -y git vim build-essential python3-dev python3-venv && \ + rm -rf /var/lib/apt/lists/* + +RUN git clone https://github.com/oobabooga/GPTQ-for-LLaMa /build + +WORKDIR /build + +RUN python3 -m venv /build/venv +RUN . /build/venv/bin/activate && \ + pip3 install --upgrade pip setuptools && \ + pip3 install torch torchvision torchaudio && \ + pip3 install -r requirements.txt + +# https://developer.nvidia.com/cuda-gpus +# for a rtx 2060: ARG TORCH_CUDA_ARCH_LIST="7.5" +ARG TORCH_CUDA_ARCH_LIST="3.5;5.0;6.0;6.1;7.0;7.5;8.0;8.6+PTX" +RUN . /build/venv/bin/activate && \ + python3 setup_cuda.py bdist_wheel -d . + +FROM nvidia/cuda:11.8.0-runtime-ubuntu22.04 + +LABEL maintainer="Your Name " +LABEL description="Docker image for GPTQ-for-LLaMa and Text Generation WebUI" + +RUN apt-get update && \ + apt-get install --no-install-recommends -y libportaudio2 libasound-dev git python3 python3-pip make g++ && \ + rm -rf /var/lib/apt/lists/* + +RUN --mount=type=cache,target=/root/.cache/pip pip3 install virtualenv +RUN mkdir /app + +WORKDIR /app + +ARG WEBUI_VERSION +RUN test -n "${WEBUI_VERSION}" && git reset --hard ${WEBUI_VERSION} || echo "Using provided webui source" + +RUN virtualenv /app/venv +RUN . /app/venv/bin/activate && \ + pip3 install --upgrade pip setuptools && \ + pip3 install torch torchvision torchaudio + +COPY --from=builder /build /app/repositories/GPTQ-for-LLaMa +RUN . /app/venv/bin/activate && \ + pip3 install /app/repositories/GPTQ-for-LLaMa/*.whl + +COPY extensions/api/requirements.txt /app/extensions/api/requirements.txt +COPY extensions/elevenlabs_tts/requirements.txt /app/extensions/elevenlabs_tts/requirements.txt +COPY extensions/google_translate/requirements.txt /app/extensions/google_translate/requirements.txt +COPY extensions/silero_tts/requirements.txt /app/extensions/silero_tts/requirements.txt +COPY extensions/whisper_stt/requirements.txt /app/extensions/whisper_stt/requirements.txt +RUN --mount=type=cache,target=/root/.cache/pip . /app/venv/bin/activate && cd extensions/api && pip3 install -r requirements.txt +RUN --mount=type=cache,target=/root/.cache/pip . /app/venv/bin/activate && cd extensions/elevenlabs_tts && pip3 install -r requirements.txt +RUN --mount=type=cache,target=/root/.cache/pip . /app/venv/bin/activate && cd extensions/google_translate && pip3 install -r requirements.txt +RUN --mount=type=cache,target=/root/.cache/pip . /app/venv/bin/activate && cd extensions/silero_tts && pip3 install -r requirements.txt +RUN --mount=type=cache,target=/root/.cache/pip . /app/venv/bin/activate && cd extensions/whisper_stt && pip3 install -r requirements.txt + +COPY requirements.txt /app/requirements.txt +RUN . /app/venv/bin/activate && \ + pip3 install -r requirements.txt + +RUN cp /app/venv/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cuda118.so /app/venv/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cpu.so + +COPY . /app/ +ENV CLI_ARGS="" +CMD . /app/venv/bin/activate && python3 server.py ${CLI_ARGS} diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..bc59dc3bb11d6ffcb692ef8e7a84f3054b126d4d --- /dev/null +++ b/docker/docker-compose.yml @@ -0,0 +1,32 @@ +version: "3.3" +services: + text-generation-webui: + build: + context: . + args: + # specify which cuda version your card supports: https://developer.nvidia.com/cuda-gpus + TORCH_CUDA_ARCH_LIST: ${TORCH_CUDA_ARCH_LIST} + WEBUI_VERSION: ${WEBUI_VERSION} + env_file: .env + ports: + - "${HOST_PORT}:${CONTAINER_PORT}" + - "${HOST_API_PORT}:${CONTAINER_API_PORT}" + - "${HOST_API_STREAM_PORT}:${CONTAINER_API_STREAM_PORT}" + stdin_open: true + tty: true + volumes: + - ./characters:/app/characters + - ./extensions:/app/extensions + - ./loras:/app/loras + - ./models:/app/models + - ./presets:/app/presets + - ./prompts:/app/prompts + - ./softprompts:/app/softprompts + - ./training:/app/training + deploy: + resources: + reservations: + devices: + - driver: nvidia + device_ids: ['0'] + capabilities: [gpu] diff --git a/docs/Chat-mode.md b/docs/Chat-mode.md new file mode 100644 index 0000000000000000000000000000000000000000..08dd290dadbd8a590ace65d557b8916a2707fc26 --- /dev/null +++ b/docs/Chat-mode.md @@ -0,0 +1,45 @@ +## Chat characters + +Custom chat mode characters are defined by `.yaml` files inside the `characters` folder. An example is included: [Example.yaml](https://github.com/oobabooga/text-generation-webui/blob/main/characters/Example.yaml) + +The following fields may be defined: + +| Field | Description | +|-------|-------------| +| `name` or `bot` | The character's name. | +| `your_name` or `user` (optional) | Your name. This overwrites what you had previously written in the `Your name` field in the interface. | +| `context` | A string that appears at the top of the prompt. It usually contains a description of the character's personality. | +| `greeting` (optional) | The character's opening message when a new conversation is started. | +| `example_dialogue` (optional) | A few example messages to guide the model. | +| `turn_template` (optional) | Used to define where the spaces and new line characters should be in Instruct mode. See the characters in `characters/instruction-following` for examples. | + +#### Special tokens + +* `{{char}}` or ``: are replaced with the character's name +* `{{user}}` or ``: are replaced with your name + +These replacements happen when the character is loaded, and they apply to the `context`, `greeting`, and `example_dialogue` fields. + +#### How do I add a profile picture for my character? + +Put an image with the same name as your character's yaml file into the `characters` folder. For example, if your bot is `Character.yaml`, add `Character.jpg` or `Character.png` to the folder. + +#### Is the chat history truncated in the prompt? + +Once your prompt reaches the 2048 token limit, old messages will be removed one at a time. The context string will always stay at the top of the prompt and will never get truncated. + +#### Pygmalion format characters + +These are also supported out of the box. Simply put the JSON file in the `characters` folder, or upload it directly from the web UI by clicking on the "Upload character" tab at the bottom. + +## Chat styles + +Custom chat styles can be defined in the `text-generation-webui/css` folder. Simply create a new file with name starting in `chat_style-` and ending in `.css` and it will automatically appear in the "Chat style" dropdown menu in the interface. Examples: + +``` +chat_style-cai-chat.css +chat_style-TheEncrypted777.css +chat_style-wpp.css +``` + +You should use the same class names as in `chat_style-cai-chat.css` in your custom style. \ No newline at end of file diff --git a/docs/DeepSpeed.md b/docs/DeepSpeed.md new file mode 100644 index 0000000000000000000000000000000000000000..6170f6819ca072ff50fd1146b64d73f74ab00473 --- /dev/null +++ b/docs/DeepSpeed.md @@ -0,0 +1,24 @@ +An alternative way of reducing the GPU memory usage of models is to use the `DeepSpeed ZeRO-3` optimization. + +With this, I have been able to load a 6b model (GPT-J 6B) with less than 6GB of VRAM. The speed of text generation is very decent and much better than what would be accomplished with `--auto-devices --gpu-memory 6`. + +As far as I know, DeepSpeed is only available for Linux at the moment. + +### How to use it + +1. Install DeepSpeed: + +``` +conda install -c conda-forge mpi4py mpich +pip install -U deepspeed +``` + +2. Start the web UI replacing `python` with `deepspeed --num_gpus=1` and adding the `--deepspeed` flag. Example: + +``` +deepspeed --num_gpus=1 server.py --deepspeed --chat --model gpt-j-6B +``` + +### Learn more + +For more information, check out [this comment](https://github.com/oobabooga/text-generation-webui/issues/40#issuecomment-1412038622) by 81300, who came up with the DeepSpeed support in this web UI. \ No newline at end of file diff --git a/docs/Docker.md b/docs/Docker.md new file mode 100644 index 0000000000000000000000000000000000000000..b1e92253cd72423a86d72f6bb057da9bed19a4bc --- /dev/null +++ b/docs/Docker.md @@ -0,0 +1,181 @@ +Docker Compose is a way of installing and launching the web UI in an isolated Ubuntu image using only a few commands. + +In order to create the image as described in the main README, you must have docker compose 2.17 or higher: + +``` +~$ docker compose version +Docker Compose version v2.17.2 +``` + +# Intructions by [@loeken](https://github.com/loeken) + +- [Ubuntu 22.04](#ubuntu-2204) + - [0. youtube video](#0-youtube-video) + - [1. update the drivers](#1-update-the-drivers) + - [2. reboot](#2-reboot) + - [3. install docker](#3-install-docker) + - [4. docker \& container toolkit](#4-docker--container-toolkit) + - [5. clone the repo](#5-clone-the-repo) + - [6. prepare models](#6-prepare-models) + - [7. prepare .env file](#7-prepare-env-file) + - [8. startup docker container](#8-startup-docker-container) +- [Manjaro](#manjaro) + - [update the drivers](#update-the-drivers) + - [reboot](#reboot) + - [docker \& container toolkit](#docker--container-toolkit) + - [continue with ubuntu task](#continue-with-ubuntu-task) +- [Windows](#windows) + - [0. youtube video](#0-youtube-video-1) + - [1. choco package manager](#1-choco-package-manager) + - [2. install drivers/dependencies](#2-install-driversdependencies) + - [3. install wsl](#3-install-wsl) + - [4. reboot](#4-reboot) + - [5. git clone \&\& startup](#5-git-clone--startup) + - [6. prepare models](#6-prepare-models-1) + - [7. startup](#7-startup) +- [notes](#notes) + +# Ubuntu 22.04 + +## 0. youtube video +A video walking you through the setup can be found here: + +[![oobabooga text-generation-webui setup in docker on ubuntu 22.04](https://img.youtube.com/vi/ELkKWYh8qOk/0.jpg)](https://www.youtube.com/watch?v=ELkKWYh8qOk) + + +## 1. update the drivers +in the the “software updater” update drivers to the last version of the prop driver. + +## 2. reboot +to switch using to new driver + +## 3. install docker +```bash +sudo apt update +sudo apt-get install curl +sudo mkdir -m 0755 -p /etc/apt/keyrings +curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg +echo \ + "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \ + "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \ + sudo tee /etc/apt/sources.list.d/docker.list > /dev/null +sudo apt update +sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin docker-compose -y +sudo usermod -aG docker $USER +newgrp docker +``` + +## 4. docker & container toolkit +```bash +curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg +echo "deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://nvidia.github.io/libnvidia-container/stable/ubuntu22.04/amd64 /" | \ +sudo tee /etc/apt/sources.list.d/nvidia.list > /dev/null +sudo apt update +sudo apt install nvidia-docker2 nvidia-container-runtime -y +sudo systemctl restart docker +``` + +## 5. clone the repo +``` +git clone https://github.com/oobabooga/text-generation-webui +cd text-generation-webui +``` + +## 6. prepare models +download and place the models inside the models folder. tested with: + +4bit +https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1483891617 +https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1483941105 + +8bit: +https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1484235789 + +## 7. prepare .env file +edit .env values to your needs. +```bash +cp .env.example .env +nano .env +``` + +## 8. startup docker container +```bash +docker compose up --build +``` + +# Manjaro +manjaro/arch is similar to ubuntu just the dependency installation is more convenient + +## update the drivers +```bash +sudo mhwd -a pci nonfree 0300 +``` +## reboot +```bash +reboot +``` +## docker & container toolkit +```bash +yay -S docker docker-compose buildkit gcc nvidia-docker +sudo usermod -aG docker $USER +newgrp docker +sudo systemctl restart docker # required by nvidia-container-runtime +``` + +## continue with ubuntu task +continue at [5. clone the repo](#5-clone-the-repo) + +# Windows +## 0. youtube video +A video walking you through the setup can be found here: +[![oobabooga text-generation-webui setup in docker on windows 11](https://img.youtube.com/vi/ejH4w5b5kFQ/0.jpg)](https://www.youtube.com/watch?v=ejH4w5b5kFQ) + +## 1. choco package manager +install package manager (https://chocolatey.org/ ) +``` +Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) +``` + +## 2. install drivers/dependencies +``` +choco install nvidia-display-driver cuda git docker-desktop +``` + +## 3. install wsl +wsl --install + +## 4. reboot +after reboot enter username/password in wsl + +## 5. git clone && startup +clone the repo and edit .env values to your needs. +``` +cd Desktop +git clone https://github.com/oobabooga/text-generation-webui +cd text-generation-webui +COPY .env.example .env +notepad .env +``` + +## 6. prepare models +download and place the models inside the models folder. tested with: + +4bit https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1483891617 https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1483941105 + +8bit: https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1484235789 + +## 7. startup +``` +docker compose up +``` + +# notes + +on older ubuntus you can manually install the docker compose plugin like this: +``` +DOCKER_CONFIG=${DOCKER_CONFIG:-$HOME/.docker} +mkdir -p $DOCKER_CONFIG/cli-plugins +curl -SL https://github.com/docker/compose/releases/download/v2.17.2/docker-compose-linux-x86_64 -o $DOCKER_CONFIG/cli-plugins/docker-compose +chmod +x $DOCKER_CONFIG/cli-plugins/docker-compose +export PATH="$HOME/.docker/cli-plugins:$PATH" +``` diff --git a/docs/Extensions.md b/docs/Extensions.md new file mode 100644 index 0000000000000000000000000000000000000000..0e396ce2c350242abf45056f869e27c3e3381de7 --- /dev/null +++ b/docs/Extensions.md @@ -0,0 +1,220 @@ +Extensions are defined by files named `script.py` inside subfolders of `text-generation-webui/extensions`. They are loaded at startup if specified with the `--extensions` flag. + +For instance, `extensions/silero_tts/script.py` gets loaded with `python server.py --extensions silero_tts`. + +## [text-generation-webui-extensions](https://github.com/oobabooga/text-generation-webui-extensions) + +The link above contains a directory of user extensions for text-generation-webui. + +If you create an extension, you are welcome to host it in a GitHub repository and submit it to the list above. + +## Built-in extensions + +Most of these have been created by the extremely talented contributors that you can find here: [contributors](https://github.com/oobabooga/text-generation-webui/graphs/contributors?from=2022-12-18&to=&type=a). + +|Extension|Description| +|---------|-----------| +|[api](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/api)| Creates an API with two endpoints, one for streaming at `/api/v1/stream` port 5005 and another for blocking at `/api/v1/generate` port 5000. This is the main API for this web UI. | +|[google_translate](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/google_translate)| Automatically translates inputs and outputs using Google Translate.| +|[character_bias](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/character_bias)| Just a very simple example that biases the bot's responses in chat mode.| +|[gallery](https://github.com/oobabooga/text-generation-webui/blob/main/extensions/gallery/)| Creates a gallery with the chat characters and their pictures. | +|[silero_tts](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/silero_tts)| Text-to-speech extension using [Silero](https://github.com/snakers4/silero-models). When used in chat mode, it replaces the responses with an audio widget. | +|[elevenlabs_tts](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/elevenlabs_tts)| Text-to-speech extension using the [ElevenLabs](https://beta.elevenlabs.io/) API. You need an API key to use it. | +|[send_pictures](https://github.com/oobabooga/text-generation-webui/blob/main/extensions/send_pictures/)| Creates an image upload field that can be used to send images to the bot in chat mode. Captions are automatically generated using BLIP. | +|[whisper_stt](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/whisper_stt)| Allows you to enter your inputs in chat mode using your microphone. | +|[sd_api_pictures](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/sd_api_pictures)| Allows you to request pictures from the bot in chat mode, which will be generated using the AUTOMATIC1111 Stable Diffusion API. See examples [here](https://github.com/oobabooga/text-generation-webui/pull/309). | +|[multimodal](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/multimodal) | Adds multimodality support (text+images). For a detailed description see [README.md](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/multimodal/README.md) in the extension directory. | +|[openai](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai)| Creates an API that mimics the OpenAI API and can be used as a drop-in replacement. | +|[superbooga](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/superbooga)| An extension that uses ChromaDB to create an arbitrarily large pseudocontext, taking as input text files, URLs, or pasted text. Based on https://github.com/kaiokendev/superbig. | + +## How to write an extension + +script.py may define the special functions and variables below. + +#### Predefined functions + +| Function | Description | +|-------------|-------------| +| `def ui()` | Creates custom gradio elements when the UI is launched. | +| `def custom_css()` | Returns custom CSS as a string. It is applied whenever the web UI is loaded. | +| `def custom_js()` | Same as above but for javascript. | +| `def input_modifier(string)` | Modifies the input string before it enters the model. In chat mode, it is applied to the user message. Otherwise, it is applied to the entire prompt. | +| `def output_modifier(string)` | Modifies the output string before it is presented in the UI. In chat mode, it is applied to the bot's reply. Otherwise, it is applied to the entire output. | +| `def state_modifier(state)` | Modifies the dictionary containing the UI input parameters before it is used by the text generation functions. | +| `def bot_prefix_modifier(string)` | Applied in chat mode to the prefix for the bot's reply. | +| `def custom_generate_reply(...)` | Overrides the main text generation function. | +| `def custom_generate_chat_prompt(...)` | Overrides the prompt generator in chat mode. | +| `def tokenizer_modifier(state, prompt, input_ids, input_embeds)` | Modifies the `input_ids`/`input_embeds` fed to the model. Should return `prompt`, `input_ids`, `input_embeds`. See the `multimodal` extension for an example. | +| `def custom_tokenized_length(prompt)` | Used in conjunction with `tokenizer_modifier`, returns the length in tokens of `prompt`. See the `multimodal` extension for an example. | + +#### `params` dictionary + +In this dictionary, `display_name` is used to define the displayed name of the extension in the UI, and `is_tab` is used to define whether the extension should appear in a new tab. By default, extensions appear at the bottom of the "Text generation" tab. + +Example: + +```python +params = { + "display_name": "Google Translate", + "is_tab": True, +} +``` + +Additionally, `params` may contain variables that you want to be customizable through a `settings.json` file. For instance, assuming the extension is in `extensions/google_translate`, the variable `language string` in + +```python +params = { + "display_name": "Google Translate", + "is_tab": True, + "language string": "jp" +} +``` + +can be customized by adding a key called `google_translate-language string` to `settings.json`: + +```python +"google_translate-language string": "fr", +``` + +That is, the syntax is `extension_name-variable_name`. + +#### `input_hijack` dictionary + +```python +input_hijack = { + 'state': False, + 'value': ["", ""] +} +``` +This is only used in chat mode. If your extension sets `input_hijack['state'] = True` at any moment, the next call to `modules.chat.chatbot_wrapper` will use the values inside `input_hijack['value']` as the user input for text generation. See the `send_pictures` extension above for an example. + +Additionally, your extension can set the value to be a callback in the form of `def cb(text: str, visible_text: str) -> [str, str]`. See the `multimodal` extension above for an example. + +## Using multiple extensions at the same time + +In order to use your extension, you must start the web UI with the `--extensions` flag followed by the name of your extension (the folder under `text-generation-webui/extension` where `script.py` resides). + +You can activate more than one extension at a time by providing their names separated by spaces. The input, output, and bot prefix modifiers will be applied in the specified order. + + +``` +python server.py --extensions enthusiasm translate # First apply enthusiasm, then translate +python server.py --extensions translate enthusiasm # First apply translate, then enthusiasm +``` + +Do note, that for: +- `custom_generate_chat_prompt` +- `custom_generate_reply` +- `tokenizer_modifier` +- `custom_tokenized_length` + +only the first declaration encountered will be used and the rest will be ignored. + +## The `bot_prefix_modifier` + +In chat mode, this function modifies the prefix for a new bot message. For instance, if your bot is named `Marie Antoinette`, the default prefix for a new message will be + +``` +Marie Antoinette: +``` + +Using `bot_prefix_modifier`, you can change it to: + +``` +Marie Antoinette: *I am very enthusiastic* +``` + +Marie Antoinette will become very enthusiastic in all her messages. + +## `custom_generate_reply` example + +Once defined in a `script.py`, this function is executed in place of the main generation functions. You can use it to connect the web UI to an external API, or to load a custom model that is not supported yet. + +Note that in chat mode, this function must only return the new text, whereas in other modes it must return the original prompt + the new text. + +```python +import datetime + +def custom_generate_reply(question, original_question, seed, state, eos_token, stopping_strings): + cumulative = '' + for i in range(10): + cumulative += f"Counting: {i}...\n" + yield cumulative + + cumulative += f"Done! {str(datetime.datetime.now())}" + yield cumulative +``` + +## `custom_generate_chat_prompt` example + +Below is an extension that just reproduces the default prompt generator in `modules/chat.py`. You can modify it freely to come up with your own prompts in chat mode. + +```python +def custom_generate_chat_prompt(user_input, state, **kwargs): + impersonate = kwargs['impersonate'] if 'impersonate' in kwargs else False + _continue = kwargs['_continue'] if '_continue' in kwargs else False + also_return_rows = kwargs['also_return_rows'] if 'also_return_rows' in kwargs else False + is_instruct = state['mode'] == 'instruct' + rows = [state['context'] if is_instruct else f"{state['context'].strip()}\n"] + min_rows = 3 + + # Finding the maximum prompt size + chat_prompt_size = state['chat_prompt_size'] + if shared.soft_prompt: + chat_prompt_size -= shared.soft_prompt_tensor.shape[1] + + max_length = min(get_max_prompt_length(state), chat_prompt_size) + + # Building the turn templates + if 'turn_template' not in state or state['turn_template'] == '': + if is_instruct: + template = '<|user|>\n<|user-message|>\n<|bot|>\n<|bot-message|>\n' + else: + template = '<|user|>: <|user-message|>\n<|bot|>: <|bot-message|>\n' + else: + template = state['turn_template'].replace(r'\n', '\n') + + replacements = { + '<|user|>': state['name1'].strip(), + '<|bot|>': state['name2'].strip(), + } + + user_turn = replace_all(template.split('<|bot|>')[0], replacements) + bot_turn = replace_all('<|bot|>' + template.split('<|bot|>')[1], replacements) + user_turn_stripped = replace_all(user_turn.split('<|user-message|>')[0], replacements) + bot_turn_stripped = replace_all(bot_turn.split('<|bot-message|>')[0], replacements) + + # Building the prompt + i = len(shared.history['internal']) - 1 + while i >= 0 and get_encoded_length(''.join(rows)) < max_length: + if _continue and i == len(shared.history['internal']) - 1: + rows.insert(1, bot_turn_stripped + shared.history['internal'][i][1].strip()) + else: + rows.insert(1, bot_turn.replace('<|bot-message|>', shared.history['internal'][i][1].strip())) + + string = shared.history['internal'][i][0] + if string not in ['', '<|BEGIN-VISIBLE-CHAT|>']: + rows.insert(1, replace_all(user_turn, {'<|user-message|>': string.strip(), '<|round|>': str(i)})) + + i -= 1 + + if impersonate: + min_rows = 2 + rows.append(user_turn_stripped.rstrip(' ')) + elif not _continue: + # Adding the user message + if len(user_input) > 0: + rows.append(replace_all(user_turn, {'<|user-message|>': user_input.strip(), '<|round|>': str(len(shared.history["internal"]))})) + + # Adding the Character prefix + rows.append(apply_extensions("bot_prefix", bot_turn_stripped.rstrip(' '))) + + while len(rows) > min_rows and get_encoded_length(''.join(rows)) >= max_length: + rows.pop(1) + + prompt = ''.join(rows) + if also_return_rows: + return prompt, rows + else: + return prompt +``` diff --git a/docs/FlexGen.md b/docs/FlexGen.md new file mode 100644 index 0000000000000000000000000000000000000000..dce71f9e6e35ab1f55d8379852316f55b013962a --- /dev/null +++ b/docs/FlexGen.md @@ -0,0 +1,64 @@ +>FlexGen is a high-throughput generation engine for running large language models with limited GPU memory (e.g., a 16GB T4 GPU or a 24GB RTX3090 gaming card!). + +https://github.com/FMInference/FlexGen + +## Installation + +No additional installation steps are necessary. FlexGen is in the `requirements.txt` file for this project. + +## Converting a model + +FlexGen only works with the OPT model, and it needs to be converted to numpy format before starting the web UI: + +``` +python convert-to-flexgen.py models/opt-1.3b/ +``` + +The output will be saved to `models/opt-1.3b-np/`. + +## Usage + +The basic command is the following: + +``` +python server.py --model opt-1.3b --flexgen +``` + +For large models, the RAM usage may be too high and your computer may freeze. If that happens, you can try this: + +``` +python server.py --model opt-1.3b --flexgen --compress-weight +``` + +With this second command, I was able to run both OPT-6.7b and OPT-13B with **2GB VRAM**, and the speed was good in both cases. + +You can also manually set the offload strategy with + +``` +python server.py --model opt-1.3b --flexgen --percent 0 100 100 0 100 0 +``` + +where the six numbers after `--percent` are: + +``` +the percentage of weight on GPU +the percentage of weight on CPU +the percentage of attention cache on GPU +the percentage of attention cache on CPU +the percentage of activations on GPU +the percentage of activations on CPU +``` + +You should typically only change the first two numbers. If their sum is less than 100, the remaining layers will be offloaded to the disk, by default into the `text-generation-webui/cache` folder. + +## Performance + +In my experiments with OPT-30B using a RTX 3090 on Linux, I have obtained these results: + +* `--flexgen --compress-weight --percent 0 100 100 0 100 0`: 0.99 seconds per token. +* `--flexgen --compress-weight --percent 100 0 100 0 100 0`: 0.765 seconds per token. + +## Limitations + +* Only works with the OPT models. +* Only two generation parameters are available: `temperature` and `do_sample`. \ No newline at end of file diff --git a/docs/GPTQ-models-(4-bit-mode).md b/docs/GPTQ-models-(4-bit-mode).md new file mode 100644 index 0000000000000000000000000000000000000000..0ec28fa6c6be7a3d8d22c76cde53a1bcde06f6f2 --- /dev/null +++ b/docs/GPTQ-models-(4-bit-mode).md @@ -0,0 +1,144 @@ +In 4-bit mode, models are loaded with just 25% of their regular VRAM usage. So LLaMA-7B fits into a 6GB GPU, and LLaMA-30B fits into a 24GB GPU. + +This is possible thanks to [@qwopqwop200](https://github.com/qwopqwop200/GPTQ-for-LLaMa)'s adaptation of the GPTQ algorithm for LLaMA: https://github.com/qwopqwop200/GPTQ-for-LLaMa + +GPTQ is a clever quantization algorithm that lightly reoptimizes the weights during quantization so that the accuracy loss is compensated relative to a round-to-nearest quantization. See the paper for more details: https://arxiv.org/abs/2210.17323 + +## GPTQ-for-LLaMa branches + +Different branches of GPTQ-for-LLaMa are available: + +| Branch | Comment | +|----|----| +| [Old CUDA branch (recommended)](https://github.com/oobabooga/GPTQ-for-LLaMa/) | The fastest branch, works on Windows and Linux. | +| [Up-to-date triton branch](https://github.com/qwopqwop200/GPTQ-for-LLaMa) | Slightly more precise than the old CUDA branch from 13b upwards, significantly more precise for 7b. 2x slower for small context size and only works on Linux. | +| [Up-to-date CUDA branch](https://github.com/qwopqwop200/GPTQ-for-LLaMa/tree/cuda) | As precise as the up-to-date triton branch, 10x slower than the old cuda branch for small context size. | + +Overall, I recommend using the old CUDA branch. It is included by default in the one-click-installer for this web UI. + +## Installation + +### Step 0: install nvcc + +``` +conda activate textgen +conda install -c conda-forge cudatoolkit-dev +``` + +The command above takes some 10 minutes to run and shows no progress bar or updates along the way. + +See this issue for more details: https://github.com/oobabooga/text-generation-webui/issues/416#issuecomment-1475078571 + +### Step 1: install GPTQ-for-LLaMa + +Clone the GPTQ-for-LLaMa repository into the `text-generation-webui/repositories` subfolder and install it: + +``` +mkdir repositories +cd repositories +git clone https://github.com/oobabooga/GPTQ-for-LLaMa.git -b cuda +cd GPTQ-for-LLaMa +python setup_cuda.py install +``` + +You are going to need to have a C++ compiler installed into your system for the last command. On Linux, `sudo apt install build-essential` or equivalent is enough. + +If you want to you to use the up-to-date CUDA or triton branches instead of the old CUDA branch, use these commands: + +``` +cd repositories +rm -r GPTQ-for-LLaMa +pip uninstall -y quant-cuda +git clone https://github.com/qwopqwop200/GPTQ-for-LLaMa.git -b cuda +... +``` + +``` +cd repositories +rm -r GPTQ-for-LLaMa +pip uninstall -y quant-cuda +git clone https://github.com/qwopqwop200/GPTQ-for-LLaMa.git -b triton +... +``` + + +https://github.com/qwopqwop200/GPTQ-for-LLaMa + +### Step 2: get the pre-converted weights + +* Converted without `group-size` (better for the 7b model): https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1483891617 +* Converted with `group-size` (better from 13b upwards): https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1483941105 + +⚠️ The tokenizer files in the sources above may be outdated. Make sure to obtain the universal LLaMA tokenizer as described [here](https://github.com/oobabooga/text-generation-webui/blob/main/docs/LLaMA-model.md#option-1-pre-converted-weights). + +### Step 3: Start the web UI: + +For the models converted without `group-size`: + +``` +python server.py --model llama-7b-4bit +``` + +For the models converted with `group-size`: + +``` +python server.py --model llama-13b-4bit-128g +``` + +The command-line flags `--wbits` and `--groupsize` are automatically detected based on the folder names, but you can also specify them manually like + +``` +python server.py --model llama-13b-4bit-128g --wbits 4 --groupsize 128 +``` + +## CPU offloading + +It is possible to offload part of the layers of the 4-bit model to the CPU with the `--pre_layer` flag. The higher the number after `--pre_layer`, the more layers will be allocated to the GPU. + +With this command, I can run llama-7b with 4GB VRAM: + +``` +python server.py --model llama-7b-4bit --pre_layer 20 +``` + +This is the performance: + +``` +Output generated in 123.79 seconds (1.61 tokens/s, 199 tokens) +``` + +You can also use multiple GPUs with `pre_layer` if using the oobabooga fork of GPTQ, eg `--pre_layer 30 60` will load a LLaMA-30B model half onto your first GPU and half onto your second, or `--pre_layer 20 40` will load 20 layers onto GPU-0, 20 layers onto GPU-1, and 20 layers offloaded to CPU. + +## Using LoRAs in 4-bit mode + +At the moment, this feature is not officially supported by the relevant libraries, but a patch exists and is supported by this web UI: https://github.com/johnsmith0031/alpaca_lora_4bit + +In order to use it: + +1. Make sure that your requirements are up to date: + +``` +cd text-generation-webui +pip install -r requirements.txt --upgrade +``` + +2. Clone `johnsmith0031/alpaca_lora_4bit` into the repositories folder: + +``` +cd text-generation-webui/repositories +git clone https://github.com/johnsmith0031/alpaca_lora_4bit +``` + +⚠️ I have tested it with the following commit specifically: `2f704b93c961bf202937b10aac9322b092afdce0` + +3. Install https://github.com/sterlind/GPTQ-for-LLaMa with this command: + +``` +pip install git+https://github.com/sterlind/GPTQ-for-LLaMa.git@lora_4bit +``` + +4. Start the UI with the `--monkey-patch` flag: + +``` +python server.py --model llama-7b-4bit-128g --listen --lora tloen_alpaca-lora-7b --monkey-patch +``` diff --git a/docs/LLaMA-model.md b/docs/LLaMA-model.md new file mode 100644 index 0000000000000000000000000000000000000000..338d458b13b56b3d0f02dd3f4b7d5156a82b88e9 --- /dev/null +++ b/docs/LLaMA-model.md @@ -0,0 +1,45 @@ +LLaMA is a Large Language Model developed by Meta AI. + +It was trained on more tokens than previous models. The result is that the smallest version with 7 billion parameters has similar performance to GPT-3 with 175 billion parameters. + +This guide will cover usage through the official `transformers` implementation. For 4-bit mode, head over to [GPTQ models (4 bit mode) +](GPTQ-models-(4-bit-mode).md). + +## Getting the weights + +### Option 1: pre-converted weights + +* Torrent: https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1484235789 +* Direct download: https://huggingface.co/Neko-Institute-of-Science + +⚠️ The tokenizers for the Torrent source above and also for many LLaMA fine-tunes available on Hugging Face may be outdated, so I recommend downloading the following universal LLaMA tokenizer: + +``` +python download-model.py oobabooga/llama-tokenizer +``` + +Once downloaded, it will be automatically applied to **every** `LlamaForCausalLM` model that you try to load. + +### Option 2: convert the weights yourself + +1. Install the `protobuf` library: + +``` +pip install protobuf==3.20.1 +``` + +2. Use the script below to convert the model in `.pth` format that you, a fellow academic, downloaded using Meta's official link: + +### [convert_llama_weights_to_hf.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/convert_llama_weights_to_hf.py) + +``` +python convert_llama_weights_to_hf.py --input_dir /path/to/LLaMA --model_size 7B --output_dir /tmp/outputs/llama-7b +``` + +3. Move the `llama-7b` folder inside your `text-generation-webui/models` folder. + +## Starting the web UI + +```python +python server.py --model llama-7b +``` diff --git a/docs/Low-VRAM-guide.md b/docs/Low-VRAM-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..1dc86f9c7f764a886c454f7f76a2a89a77140655 --- /dev/null +++ b/docs/Low-VRAM-guide.md @@ -0,0 +1,51 @@ +If you GPU is not large enough to fit a model, try these in the following order: + +### Load the model in 8-bit mode + +``` +python server.py --load-in-8bit +``` + +This reduces the memory usage by half with no noticeable loss in quality. Only newer GPUs support 8-bit mode. + +### Split the model across your GPU and CPU + +``` +python server.py --auto-devices +``` + +If you can load the model with this command but it runs out of memory when you try to generate text, try increasingly limiting the amount of memory allocated to the GPU until the error stops happening: + +``` +python server.py --auto-devices --gpu-memory 10 +python server.py --auto-devices --gpu-memory 9 +python server.py --auto-devices --gpu-memory 8 +... +``` + +where the number is in GiB. + +For finer control, you can also specify the unit in MiB explicitly: + +``` +python server.py --auto-devices --gpu-memory 8722MiB +python server.py --auto-devices --gpu-memory 4725MiB +python server.py --auto-devices --gpu-memory 3500MiB +... +``` + +Additionally, you can also set the `--no-cache` value to reduce the GPU usage while generating text at a performance cost. This may allow you to set a higher value for `--gpu-memory`, resulting in a net performance gain. + +### Send layers to a disk cache + +As a desperate last measure, you can split the model across your GPU, CPU, and disk: + +``` +python server.py --auto-devices --disk +``` + +With this, I am able to load a 30b model into my RTX 3090, but it takes 10 seconds to generate 1 word. + +### DeepSpeed (experimental) + +An experimental alternative to all of the above is to use DeepSpeed: [guide](DeepSpeed.md). diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..65dadd7cfc906247d9c6995896ba6a144a0d31c1 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,19 @@ +# text-generation-webui documentation + +## Table of contents + +* [GPTQ models (4 bit mode)](GPTQ-models-(4-bit-mode).md) +* [LLaMA model](LLaMA-model.md) +* [Using LoRAs](Using-LoRAs.md) +* [llama.cpp models](llama.cpp-models.md) +* [RWKV model](RWKV-model.md) +* [Extensions](Extensions.md) +* [Chat mode](Chat-mode.md) +* [DeepSpeed](DeepSpeed.md) +* [FlexGen](FlexGen.md) +* [Spell book](Spell-book.md) +* [Low-VRAM-guide](Low-VRAM-guide.md) +* [System requirements](System-requirements.md) +* [Windows installation guide](Windows-installation-guide.md) +* [WSL installation guide](WSL-installation-guide.md) +* [Docker Compose](Docker.md) diff --git a/docs/RWKV-model.md b/docs/RWKV-model.md new file mode 100644 index 0000000000000000000000000000000000000000..27db3d10ca98faffee7c254a3244405f8cce2793 --- /dev/null +++ b/docs/RWKV-model.md @@ -0,0 +1,54 @@ +> RWKV: RNN with Transformer-level LLM Performance +> +> It combines the best of RNN and transformer - great performance, fast inference, saves VRAM, fast training, "infinite" ctx_len, and free sentence embedding (using the final hidden state). + +https://github.com/BlinkDL/RWKV-LM + +https://github.com/BlinkDL/ChatRWKV + +## Using RWKV in the web UI + +#### 1. Download the model + +It is available in different sizes: + +* https://huggingface.co/BlinkDL/rwkv-4-pile-3b/ +* https://huggingface.co/BlinkDL/rwkv-4-pile-7b/ +* https://huggingface.co/BlinkDL/rwkv-4-pile-14b/ + +There are also older releases with smaller sizes like: + +* https://huggingface.co/BlinkDL/rwkv-4-pile-169m/resolve/main/RWKV-4-Pile-169M-20220807-8023.pth + +Download the chosen `.pth` and put it directly in the `models` folder. + +#### 2. Download the tokenizer + +[20B_tokenizer.json](https://raw.githubusercontent.com/BlinkDL/ChatRWKV/main/v2/20B_tokenizer.json) + +Also put it directly in the `models` folder. Make sure to not rename it. It should be called `20B_tokenizer.json`. + +#### 3. Launch the web UI + +No additional steps are required. Just launch it as you would with any other model. + +``` +python server.py --listen --no-stream --model RWKV-4-Pile-169M-20220807-8023.pth +``` + +## Setting a custom strategy + +It is possible to have very fine control over the offloading and precision for the model with the `--rwkv-strategy` flag. Possible values include: + +``` +"cpu fp32" # CPU mode +"cuda fp16" # GPU mode with float16 precision +"cuda fp16 *30 -> cpu fp32" # GPU+CPU offloading. The higher the number after *, the higher the GPU allocation. +"cuda fp16i8" # GPU mode with 8-bit precision +``` + +See the README for the PyPl package for more details: https://pypi.org/project/rwkv/ + +## Compiling the CUDA kernel + +You can compile the CUDA kernel for the model with `--rwkv-cuda-on`. This should improve the performance a lot but I haven't been able to get it to work yet. \ No newline at end of file diff --git a/docs/Spell-book.md b/docs/Spell-book.md new file mode 100644 index 0000000000000000000000000000000000000000..9b7c76c953f76f8a486bbe5156de4e9ebb3f0ec0 --- /dev/null +++ b/docs/Spell-book.md @@ -0,0 +1,107 @@ +You have now entered a hidden corner of the internet. + +A confusing yet intriguing realm of paradoxes and contradictions. + +A place where you will find out that what you thought you knew, you in fact didn't know, and what you didn't know was in front of you all along. + +![](https://i.pinimg.com/originals/6e/e2/7b/6ee27bad351d3aca470d80f1033ba9c6.jpg) + +*In other words, here I will document little-known facts about this web UI that I could not find another place for in the wiki.* + +#### You can train LoRAs in CPU mode + +Load the web UI with + +``` +python server.py --cpu +``` + +and start training the LoRA from the training tab as usual. + +#### 8-bit mode works with CPU offloading + +``` +python server.py --load-in-8bit --gpu-memory 4000MiB +``` + +#### `--pre_layer`, and not `--gpu-memory`, is the right way to do CPU offloading with 4-bit models + +``` +python server.py --wbits 4 --groupsize 128 --pre_layer 20 +``` + +#### Models can be loaded in 32-bit, 16-bit, 8-bit, and 4-bit modes + +``` +python server.py --cpu +python server.py +python server.py --load-in-8bit +python server.py --wbits 4 +``` + +#### The web UI works with any version of GPTQ-for-LLaMa + +Including the up to date triton and cuda branches. But you have to delete the `repositories/GPTQ-for-LLaMa` folder and reinstall the new one every time: + +``` +cd text-generation-webui/repositories +rm -r GPTQ-for-LLaMa +pip uninstall quant-cuda +git clone https://github.com/oobabooga/GPTQ-for-LLaMa -b cuda # or any other repository and branch +cd GPTQ-for-LLaMa +python setup_cuda.py install +``` + +#### Instruction-following templates are represented as chat characters + +https://github.com/oobabooga/text-generation-webui/tree/main/characters/instruction-following + +#### The right way to run Alpaca, Open Assistant, Vicuna, etc is Instruct mode, not normal chat mode + +Otherwise the prompt will not be formatted correctly. + +1. Start the web UI with + +``` +python server.py --chat +``` + +2. Click on the "instruct" option under "Chat modes" + +3. Select the correct template in the hidden dropdown menu that will become visible. + +#### Notebook mode is best mode + +Ascended individuals have realized that notebook mode is the superset of chat mode and can do chats with ultimate flexibility, including group chats, editing replies, starting a new bot reply in a given way, and impersonating. + +#### RWKV is a RNN + +Most models are transformers, but not RWKV, which is a RNN. It's a great model. + +#### `--gpu-memory` is not a hard limit on the GPU memory + +It is simply a parameter that is passed to the `accelerate` library while loading the model. More memory will be allocated during generation. That's why this parameter has to be set to less than your total GPU memory. + +#### Contrastive search perhaps the best preset + +But it uses a ton of VRAM. + +#### You can check the sha256sum of downloaded models with the download script + +``` +python download-model.py facebook/galactica-125m --check +``` + +#### The download script continues interrupted downloads by default + +It doesn't start over. + +#### You can download models with multiple threads + +``` +python download-model.py facebook/galactica-125m --threads 8 +``` + +#### LoRAs work in 4-bit mode + +You need to follow [these instructions](GPTQ-models-(4-bit-mode).md#using-loras-in-4-bit-mode) and then start the web UI with the `--monkey-patch` flag. diff --git a/docs/System-requirements.md b/docs/System-requirements.md new file mode 100644 index 0000000000000000000000000000000000000000..3a88416d34ad7c8babd90a81db902e95288a8197 --- /dev/null +++ b/docs/System-requirements.md @@ -0,0 +1,42 @@ +These are the VRAM and RAM requirements (in MiB) to run some examples of models **in 16-bit (default) precision**: + +| model | VRAM (GPU) | RAM | +|:-----------------------|-------------:|--------:| +| arxiv_ai_gpt2 | 1512.37 | 5824.2 | +| blenderbot-1B-distill | 2441.75 | 4425.91 | +| opt-1.3b | 2509.61 | 4427.79 | +| gpt-neo-1.3b | 2605.27 | 5851.58 | +| opt-2.7b | 5058.05 | 4863.95 | +| gpt4chan_model_float16 | 11653.7 | 4437.71 | +| gpt-j-6B | 11653.7 | 5633.79 | +| galactica-6.7b | 12697.9 | 4429.89 | +| opt-6.7b | 12700 | 4368.66 | +| bloomz-7b1-p3 | 13483.1 | 4470.34 | + +#### GPU mode with 8-bit precision + +Allows you to load models that would not normally fit into your GPU. Enabled by default for 13b and 20b models in this web UI. + +| model | VRAM (GPU) | RAM | +|:---------------|-------------:|--------:| +| opt-13b | 12528.1 | 1152.39 | +| gpt-neox-20b | 20384 | 2291.7 | + +#### CPU mode (32-bit precision) + +A lot slower, but does not require a GPU. + +On my i5-12400F, 6B models take around 10-20 seconds to respond in chat mode, and around 5 minutes to generate a 200 tokens completion. + +| model | RAM | +|:-----------------------|---------:| +| arxiv_ai_gpt2 | 4430.82 | +| gpt-neo-1.3b | 6089.31 | +| opt-1.3b | 8411.12 | +| blenderbot-1B-distill | 8508.16 | +| opt-2.7b | 14969.3 | +| bloomz-7b1-p3 | 21371.2 | +| gpt-j-6B | 24200.3 | +| gpt4chan_model | 24246.3 | +| galactica-6.7b | 26561.4 | +| opt-6.7b | 29596.6 | diff --git a/docs/Training-LoRAs.md b/docs/Training-LoRAs.md new file mode 100644 index 0000000000000000000000000000000000000000..406ec1e4a135288867dc5c876594426aa827d568 --- /dev/null +++ b/docs/Training-LoRAs.md @@ -0,0 +1,167 @@ +## Training Your Own LoRAs + +The WebUI seeks to make training your own LoRAs as easy as possible. It comes down to just a few simple steps: + +### **Step 1**: Make a plan. +- What base model do you want to use? The LoRA you make has to be matched up to a single architecture (eg LLaMA-13B) and cannot be transferred to others (eg LLaMA-7B, StableLM, etc. would all be different). Derivatives of the same model (eg Alpaca finetune of LLaMA-13B) might be transferrable, but even then it's best to train exactly on what you plan to use. +- What model format do you want? At time of writing, 8-bit models are most stable, and 4-bit are supported but experimental. In the near future it is likely that 4-bit will be the best option for most users. +- What are you training it on? Do you want it to learn real information, a simple format, ...? + +### **Step 2**: Gather a dataset. +- If you use a dataset similar to the [Alpaca](https://github.com/gururise/AlpacaDataCleaned/blob/main/alpaca_data_cleaned.json) format, that is natively supported by the `Formatted Dataset` input in the WebUI, with premade formatter options. +- If you use a dataset that isn't matched to Alpaca's format, but uses the same basic JSON structure, you can make your own format file by copying `training/formats/alpaca-format.json` to a new file and [editing its content](#format-files). +- If you can get the dataset into a simple text file, that works too! You can train using the `Raw text file` input option. + - This means you can for example just copy/paste a chatlog/documentation page/whatever you want, shove it in a plain text file, and train on it. +- If you use a structured dataset not in this format, you may have to find an external way to convert it - or open an issue to request native support. + +### **Step 3**: Do the training. +- **3.1**: Load the WebUI, and your model. + - Make sure you don't have any LoRAs already loaded (unless you want to train for multi-LoRA usage). +- **3.2**: Open the `Training` tab at the top, `Train LoRA` sub-tab. +- **3.3**: Fill in the name of the LoRA, select your dataset in the dataset options. +- **3.4**: Select other parameters to your preference. See [parameters below](#parameters). +- **3.5**: click `Start LoRA Training`, and wait. + - It can take a few hours for a large dataset, or just a few minute if doing a small run. + - You may want to monitor your [loss value](#loss) while it goes. + +### **Step 4**: Evaluate your results. +- Load the LoRA under the Models Tab. +- You can go test-drive it on the `Text generation` tab, or you can use the `Perplexity evaluation` sub-tab of the `Training` tab. +- If you used the `Save every n steps` option, you can grab prior copies of the model from sub-folders within the LoRA model's folder and try them instead. + +### **Step 5**: Re-run if you're unhappy. +- Make sure to unload the LoRA before training it. +- You can simply resume a prior run - use `Copy parameters from` to select your LoRA, and edit parameters. Note that you cannot change the `Rank` of an already created LoRA. + - If you want to resume from a checkpoint saved along the way, simply copy the contents of the checkpoint folder into the LoRA's folder. + - (Note: `adapter_model.bin` is the important file that holds the actual LoRA content). + - This will start Learning Rate and Steps back to the start. If you want to resume as if you were midway through, you can adjust your Learning Rate to the last reported LR in logs and reduce your epochs. +- Or, you can start over entirely if you prefer. +- If your model is producing corrupted outputs, you probably need to start over and use a lower Learning Rate. +- If your model isn't learning detailed information but you want it to, you might need to just run more epochs, or you might need a higher Rank. +- If your model is enforcing a format you didn't want, you may need to tweak your dataset, or start over and not train as far. + +## Format Files + +If using JSON formatted datasets, they are presumed to be in the following approximate format: + +```json +[ + { + "somekey": "somevalue", + "key2": "value2" + }, + { + // etc + } +] +``` + +Where the keys (eg `somekey`, `key2` above) are standardized, and relatively consistent across the dataset, and the values (eg `somevalue`, `value2`) contain the content actually intended to be trained. + +For Alpaca, the keys are `instruction`, `input`, and `output`, wherein `input` is sometimes blank. + +A simple format file for Alpaca to be used as a chat bot is: + +```json +{ + "instruction,output": "User: %instruction%\nAssistant: %output%", + "instruction,input,output": "User: %instruction%: %input%\nAssistant: %output%" +} +``` + +Note that the keys (eg `instruction,output`) are a comma-separated list of dataset keys, and the values are a simple string that use those keys with `%%`. + +So for example if a dataset has `"instruction": "answer my question"`, then the format file's `User: %instruction%\n` will be automatically filled in as `User: answer my question\n`. + +If you have different sets of key inputs, you can make your own format file to match it. This format-file is designed to be as simple as possible to enable easy editing to match your needs. + +## Parameters + +The basic purpose and function of each parameter is documented on-page in the WebUI, so read through them in the UI to understand your options. + +That said, here's a guide to the most important parameter choices you should consider: + +### VRAM + +- First, you must consider your VRAM availability. + - Generally, under default settings, VRAM usage for training with default parameters is very close to when generating text (with 1000+ tokens of context) (ie, if you can generate text, you can train LoRAs). + - Note: worse by default in the 4-bit monkeypatch currently. Reduce `Micro Batch Size` to `1` to restore this to expectations. + - If you have VRAM to spare, setting higher batch sizes will use more VRAM and get you better quality training in exchange. + - If you have large data, setting a higher cutoff length may be beneficial, but will cost significant VRAM. If you can spare some, set your batch size to `1` and see how high you can push your cutoff length. + - If you're low on VRAM, reducing batch size or cutoff length will of course improve that. + - Don't be afraid to just try it and see what happens. If it's too much, it will just error out, and you can lower settings and try again. + +### Rank + +- Second, you want to consider the amount of learning you want. + - For example, you may wish to just learn a dialogue format (as in the case of Alpaca) in which case setting a low `Rank` value (32 or lower) works great. + - Or, you might be training on project documentation you want the bot to understand and be able to understand questions about, in which case the higher the rank, the better. + - Generally, higher Rank = more precise learning = more total content learned = more VRAM usage while training. + +### Learning Rate and Epochs + +- Third, how carefully you want it to be learned. + - In other words, how okay or not you are with the model losing unrelated understandings. + - You can control this with 3 key settings: the Learning Rate, its scheduler, and your total epochs. + - The learning rate controls how much change is made to the model by each token it sees. + - It's in scientific notation normally, so for example `3e-4` means `3 * 10^-4` which is `0.0003`. The number after `e-` controls how many `0`s are in the number. + - Higher values let training run faster, but also are more likely to corrupt prior data in the model. + - You essentially have two variables to balance: the LR, and Epochs. + - If you make LR higher, you can set Epochs equally lower to match. High LR + low epochs = very fast, low quality training. + - If you make LR low, set epochs high. Low LR + high epochs = slow but high-quality training. + - The scheduler controls change-over-time as you train - it starts high, and then goes low. This helps balance getting data in, and having decent quality, at the same time. + - You can see graphs of the different scheduler options [in the HuggingFace docs here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_1/en/main_classes/optimizer_schedules#transformers.SchedulerType) + +## Loss + +When you're running training, the WebUI's console window will log reports that include, among other things, a numeric value named `Loss`. It will start as a high number, and gradually get lower and lower as it goes. + +"Loss" in the world of AI training theoretically means "how close is the model to perfect", with `0` meaning "absolutely perfect". This is calculated by measuring the difference between the model outputting exactly the text you're training it to output, and what it actually outputs. + +In practice, a good LLM should have a very complex variable range of ideas running in its artificial head, so a loss of `0` would indicate that the model has broken and forgotten to how think about anything other than what you trained it. + +So, in effect, Loss is a balancing game: you want to get it low enough that it understands your data, but high enough that it isn't forgetting everything else. Generally, if it goes below `1.0`, it's going to start forgetting its prior memories, and you should stop training. In some cases you may prefer to take it as low as `0.5` (if you want it to be very very predictable). Different goals have different needs, so don't be afraid to experiment and see what works best for you. + +Note: if you see Loss start at or suddenly jump to exactly `0`, it is likely something has gone wrong in your training process (eg model corruption). + +## Note: 4-Bit Monkeypatch + +The [4-bit LoRA monkeypatch](GPTQ-models-(4-bit-mode).md#using-loras-in-4-bit-mode) works for training, but has side effects: +- VRAM usage is higher currently. You can reduce the `Micro Batch Size` to `1` to compensate. +- Models do funky things. LoRAs apply themselves, or refuse to apply, or spontaneously error out, or etc. It can be helpful to reload base model or restart the WebUI between training/usage to minimize chances of anything going haywire. +- Loading or working with multiple LoRAs at the same time doesn't currently work. +- Generally, recognize and treat the monkeypatch as the dirty temporary hack it is - it works, but isn't very stable. It will get better in time when everything is merged upstream for full official support. + +## Legacy notes + +LoRA training was contributed by [mcmonkey4eva](https://github.com/mcmonkey4eva) in PR [#570](https://github.com/oobabooga/text-generation-webui/pull/570). + +### Using the original alpaca-lora code + +Kept here for reference. The Training tab has much more features than this method. + +``` +conda activate textgen +git clone https://github.com/tloen/alpaca-lora +``` + +Edit those two lines in `alpaca-lora/finetune.py` to use your existing model folder instead of downloading everything from decapoda: + +``` +model = LlamaForCausalLM.from_pretrained( + "models/llama-7b", + load_in_8bit=True, + device_map="auto", +) +tokenizer = LlamaTokenizer.from_pretrained( + "models/llama-7b", add_eos_token=True +) +``` + +Run the script with: + +``` +python finetune.py +``` + +It just works. It runs at 22.32s/it, with 1170 iterations in total, so about 7 hours and a half for training a LoRA. RTX 3090, 18153MiB VRAM used, drawing maximum power (350W, room heater mode). diff --git a/docs/Using-LoRAs.md b/docs/Using-LoRAs.md new file mode 100644 index 0000000000000000000000000000000000000000..fafd6cde2d87bfdf46d942ab841a74bf50facdb5 --- /dev/null +++ b/docs/Using-LoRAs.md @@ -0,0 +1,55 @@ +Based on https://github.com/tloen/alpaca-lora + +## Instructions + +1. Download a LoRA, for instance: + +``` +python download-model.py tloen/alpaca-lora-7b +``` + +2. Load the LoRA. 16-bit, 8-bit, and CPU modes work: + +``` +python server.py --model llama-7b-hf --lora tloen_alpaca-lora-7b +python server.py --model llama-7b-hf --lora tloen_alpaca-lora-7b --load-in-8bit +python server.py --model llama-7b-hf --lora tloen_alpaca-lora-7b --cpu +``` + +* For using LoRAs in 4-bit mode, follow [these special instructions](GPTQ-models-(4-bit-mode).md#using-loras-in-4-bit-mode). + +* Instead of using the `--lora` command-line flag, you can also select the LoRA in the "Parameters" tab of the interface. + +## Prompt +For the Alpaca LoRA in particular, the prompt must be formatted like this: + +``` +Below is an instruction that describes a task. Write a response that appropriately completes the request. +### Instruction: +Write a Python script that generates text using the transformers library. +### Response: +``` + +Sample output: + +``` +Below is an instruction that describes a task. Write a response that appropriately completes the request. +### Instruction: +Write a Python script that generates text using the transformers library. +### Response: + +import transformers +from transformers import AutoTokenizer, AutoModelForCausalLM +tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") +model = AutoModelForCausalLM.from_pretrained("bert-base-uncased") +texts = ["Hello world", "How are you"] +for sentence in texts: +sentence = tokenizer(sentence) +print(f"Generated {len(sentence)} tokens from '{sentence}'") +output = model(sentences=sentence).predict() +print(f"Predicted {len(output)} tokens for '{sentence}':\n{output}") +``` + +## Training a LoRA + +You can train your own LoRAs from the `Training` tab. See [Training LoRAs](Training-LoRAs.md) for details. diff --git a/docs/WSL-installation-guide.md b/docs/WSL-installation-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..7de38b114f7b0fb6e522c20520b3aadbb8161970 --- /dev/null +++ b/docs/WSL-installation-guide.md @@ -0,0 +1,79 @@ +Guide created by [@jfryton](https://github.com/jfryton). Thank you jfryton. + +----- + +Here's an easy-to-follow, step-by-step guide for installing Windows Subsystem for Linux (WSL) with Ubuntu on Windows 10/11: + +## Step 1: Enable WSL + +1. Press the Windows key + X and click on "Windows PowerShell (Admin)" or "Windows Terminal (Admin)" to open PowerShell or Terminal with administrator privileges. +2. In the PowerShell window, type the following command and press Enter: + +``` +wsl --install +``` + +If this command doesn't work, you can enable WSL with the following command for Windows 10: + +``` +wsl --set-default-version 1 +``` + +For Windows 11, you can use: + +``` +wsl --set-default-version 2 +``` + +You may be prompted to restart your computer. If so, save your work and restart. + +## Step 2: Install Ubuntu + +1. Open the Microsoft Store. +2. Search for "Ubuntu" in the search bar. +3. Choose the desired Ubuntu version (e.g., Ubuntu 20.04 LTS) and click "Get" or "Install" to download and install the Ubuntu app. +4. Once the installation is complete, click "Launch" or search for "Ubuntu" in the Start menu and open the app. + +## Step 3: Set up Ubuntu + +1. When you first launch the Ubuntu app, it will take a few minutes to set up. Be patient as it installs the necessary files and sets up your environment. +2. Once the setup is complete, you will be prompted to create a new UNIX username and password. Choose a username and password, and make sure to remember them, as you will need them for future administrative tasks within the Ubuntu environment. + +## Step 4: Update and upgrade packages + +1. After setting up your username and password, it's a good idea to update and upgrade your Ubuntu system. Run the following commands in the Ubuntu terminal: + +``` +sudo apt update +sudo apt upgrade +``` + +2. Enter your password when prompted. This will update the package list and upgrade any outdated packages. + +Congratulations! You have now installed WSL with Ubuntu on your Windows 10/11 system. You can use the Ubuntu terminal for various tasks, like running Linux commands, installing packages, or managing files. + +You can launch your WSL Ubuntu installation by selecting the Ubuntu app (like any other program installed on your computer) or typing 'ubuntu' into Powershell or Terminal. + +## Step 5: Proceed with Linux instructions + +1. You can now follow the Linux setup instructions. If you receive any error messages about a missing tool or package, just install them using apt: + +``` +sudo apt install [missing package] +``` + +You will probably need to install build-essential + +``` +sudo apt install build-essential +``` + +If you face any issues or need to troubleshoot, you can always refer to the official Microsoft documentation for WSL: https://docs.microsoft.com/en-us/windows/wsl/ + +## Bonus: Port Forwarding + +By default, you won't be able to access the webui from another device on your local network. You will need to setup the appropriate port forwarding using the following command (using PowerShell or Terminal with administrator privileges). + +``` +netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=7860 connectaddress=localhost connectport=7860 +``` diff --git a/docs/Windows-installation-guide.md b/docs/Windows-installation-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..83b22efa38b1839d07a5a58494dbc26ba86397ee --- /dev/null +++ b/docs/Windows-installation-guide.md @@ -0,0 +1,9 @@ +If you are having trouble following the installation instructions in the README, Reddit user [Technical_Leather949](https://www.reddit.com/user/Technical_Leather949/) has created a more detailed, step-by-step guide covering: + +* Windows installation +* 8-bit mode on Windows +* LLaMA +* LLaMA 4-bit + +The guide can be found here: https://www.reddit.com/r/LocalLLaMA/comments/11o6o3f/how_to_install_llama_8bit_and_4bit/ + diff --git a/docs/llama.cpp-models.md b/docs/llama.cpp-models.md new file mode 100644 index 0000000000000000000000000000000000000000..153f70affedf55df3b58af5c46eb0396b5ecf010 --- /dev/null +++ b/docs/llama.cpp-models.md @@ -0,0 +1,43 @@ +# Using llama.cpp in the web UI + +## Setting up the models + +#### Pre-converted + +Place the model in the `models` folder, making sure that its name contains `ggml` somewhere and ends in `.bin`. + +#### Convert LLaMA yourself + +Follow the instructions in the llama.cpp README to generate the `ggml-model.bin` file: https://github.com/ggerganov/llama.cpp#usage + +## GPU offloading + +Enabled with the `--n-gpu-layers` parameter. If you have enough VRAM, use a high number like `--n-gpu-layers 200000` to offload all layers to the GPU. + +Note that you need to manually install `llama-cpp-python` with GPU support. To do that: + +#### Linux + +``` +pip uninstall -y llama-cpp-python +CMAKE_ARGS="-DLLAMA_CUBLAS=on" FORCE_CMAKE=1 pip install llama-cpp-python --no-cache-dir +``` + +#### Windows + +``` +pip uninstall -y llama-cpp-python +set CMAKE_ARGS="-DLLAMA_CUBLAS=on" +set FORCE_CMAKE=1 +pip install llama-cpp-python --no-cache-dir +``` + +Here you can find the different compilation options for OpenBLAS / cuBLAS / CLBlast: https://pypi.org/project/llama-cpp-python/ + +## Performance + +This was the performance of llama-7b int4 on my i5-12400F (cpu only): + +> Output generated in 33.07 seconds (6.05 tokens/s, 200 tokens, context 17) + +You can change the number of threads with `--threads N`. diff --git a/download-model.py b/download-model.py index 8be398c4e0d3ca0c0a915efb442f432fc2056834..44b87a8c71386bc6e1ca3ae3a3788c7283857eea 100644 --- a/download-model.py +++ b/download-model.py @@ -8,78 +8,55 @@ python download-model.py facebook/opt-1.3b import argparse import base64 +import datetime +import hashlib import json -import multiprocessing import re import sys from pathlib import Path import requests import tqdm +from tqdm.contrib.concurrent import thread_map -parser = argparse.ArgumentParser() -parser.add_argument('MODEL', type=str, default=None, nargs='?') -parser.add_argument('--branch', type=str, default='main', help='Name of the Git branch to download from.') -parser.add_argument('--threads', type=int, default=1, help='Number of files to download simultaneously.') -parser.add_argument('--text-only', action='store_true', help='Only download text files (txt/json).') -args = parser.parse_args() - -def get_file(args): - url = args[0] - output_folder = args[1] - idx = args[2] - tot = args[3] - - print(f"Downloading file {idx} of {tot}...") - r = requests.get(url, stream=True) - with open(output_folder / Path(url.split('/')[-1]), 'wb') as f: - total_size = int(r.headers.get('content-length', 0)) - block_size = 1024 - t = tqdm.tqdm(total=total_size, unit='iB', unit_scale=True) - for data in r.iter_content(block_size): - t.update(len(data)) - f.write(data) - t.close() - -def sanitize_branch_name(branch_name): - pattern = re.compile(r"^[a-zA-Z0-9._-]+$") - if pattern.match(branch_name): - return branch_name - else: - raise ValueError("Invalid branch name. Only alphanumeric characters, period, underscore and dash are allowed.") def select_model_from_default_options(): models = { - "Pygmalion 6B original": ("PygmalionAI", "pygmalion-6b", "b8344bb4eb76a437797ad3b19420a13922aaabe1"), - "Pygmalion 6B main": ("PygmalionAI", "pygmalion-6b", "main"), - "Pygmalion 6B dev": ("PygmalionAI", "pygmalion-6b", "dev"), - "Pygmalion 2.7B": ("PygmalionAI", "pygmalion-2.7b", "main"), - "Pygmalion 1.3B": ("PygmalionAI", "pygmalion-1.3b", "main"), - "Pygmalion 350m": ("PygmalionAI", "pygmalion-350m", "main"), - "OPT 6.7b": ("facebook", "opt-6.7b", "main"), - "OPT 2.7b": ("facebook", "opt-2.7b", "main"), - "OPT 1.3b": ("facebook", "opt-1.3b", "main"), - "OPT 350m": ("facebook", "opt-350m", "main"), + "OPT 6.7B": ("facebook", "opt-6.7b", "main"), + "OPT 2.7B": ("facebook", "opt-2.7b", "main"), + "OPT 1.3B": ("facebook", "opt-1.3b", "main"), + "OPT 350M": ("facebook", "opt-350m", "main"), + "GALACTICA 6.7B": ("facebook", "galactica-6.7b", "main"), + "GALACTICA 1.3B": ("facebook", "galactica-1.3b", "main"), + "GALACTICA 125M": ("facebook", "galactica-125m", "main"), + "Pythia-6.9B-deduped": ("EleutherAI", "pythia-6.9b-deduped", "main"), + "Pythia-2.8B-deduped": ("EleutherAI", "pythia-2.8b-deduped", "main"), + "Pythia-1.4B-deduped": ("EleutherAI", "pythia-1.4b-deduped", "main"), + "Pythia-410M-deduped": ("EleutherAI", "pythia-410m-deduped", "main"), } - choices = {} + choices = {} print("Select the model that you want to download:\n") - for i,name in enumerate(models): - char = chr(ord('A')+i) + for i, name in enumerate(models): + char = chr(ord('A') + i) choices[char] = name print(f"{char}) {name}") - char = chr(ord('A')+len(models)) - print(f"{char}) None of the above") + char_hugging = chr(ord('A') + len(models)) + print(f"{char_hugging}) Manually specify a Hugging Face model") + char_exit = chr(ord('A') + len(models) + 1) + print(f"{char_exit}) Do not download a model") print() print("Input> ", end='') choice = input()[0].strip().upper() - if choice == char: - print("""\nThen type the name of your desired Hugging Face model in the format organization/name. + if choice == char_exit: + exit() + elif choice == char_hugging: + print("""\nType the name of your desired Hugging Face model in the format organization/name. Examples: -PygmalionAI/pygmalion-6b facebook/opt-1.3b +EleutherAI/pythia-1.4b-deduped """) print("Input> ", end='') @@ -92,17 +69,38 @@ facebook/opt-1.3b return model, branch -def get_download_links_from_huggingface(model, branch): + +def sanitize_model_and_branch_names(model, branch): + if model[-1] == '/': + model = model[:-1] + if branch is None: + branch = "main" + else: + pattern = re.compile(r"^[a-zA-Z0-9._-]+$") + if not pattern.match(branch): + raise ValueError("Invalid branch name. Only alphanumeric characters, period, underscore and dash are allowed.") + + return model, branch + + +def get_download_links_from_huggingface(model, branch, text_only=False): base = "https://huggingface.co" - page = f"/api/models/{model}/tree/{branch}?cursor=" + page = f"/api/models/{model}/tree/{branch}" cursor = b"" links = [] + sha256 = [] classifications = [] has_pytorch = False + has_pt = False + has_ggml = False has_safetensors = False + is_lora = False while True: - content = requests.get(f"{base}{page}{cursor.decode()}").content + url = f"{base}{page}" + (f"?cursor={cursor.decode()}" if cursor else "") + r = requests.get(url, timeout=10) + r.raise_for_status() + content = r.content dict = json.loads(content) if len(dict) == 0: @@ -110,18 +108,24 @@ def get_download_links_from_huggingface(model, branch): for i in range(len(dict)): fname = dict[i]['path'] + if not is_lora and fname.endswith(('adapter_config.json', 'adapter_model.bin')): + is_lora = True - is_pytorch = re.match("pytorch_model.*\.bin", fname) - is_safetensors = re.match("model.*\.safetensors", fname) - is_tokenizer = re.match("tokenizer.*\.model", fname) - is_text = re.match(".*\.(txt|json)", fname) or is_tokenizer + is_pytorch = re.match("(pytorch|adapter)_model.*\.bin", fname) + is_safetensors = re.match(".*\.safetensors", fname) + is_pt = re.match(".*\.pt", fname) + is_ggml = re.match(".*ggml.*\.bin", fname) + is_tokenizer = re.match("(tokenizer|ice).*\.model", fname) + is_text = re.match(".*\.(txt|json|py|md)", fname) or is_tokenizer - if any((is_pytorch, is_safetensors, is_text, is_tokenizer)): + if any((is_pytorch, is_safetensors, is_pt, is_ggml, is_tokenizer, is_text)): + if 'lfs' in dict[i]: + sha256.append([fname, dict[i]['lfs']['oid']]) if is_text: links.append(f"https://huggingface.co/{model}/resolve/{branch}/{fname}") classifications.append('text') continue - if not args.text_only: + if not text_only: links.append(f"https://huggingface.co/{model}/resolve/{branch}/{fname}") if is_safetensors: has_safetensors = True @@ -129,48 +133,145 @@ def get_download_links_from_huggingface(model, branch): elif is_pytorch: has_pytorch = True classifications.append('pytorch') + elif is_pt: + has_pt = True + classifications.append('pt') + elif is_ggml: + has_ggml = True + classifications.append('ggml') cursor = base64.b64encode(f'{{"file_name":"{dict[-1]["path"]}"}}'.encode()) + b':50' cursor = base64.b64encode(cursor) cursor = cursor.replace(b'=', b'%3D') # If both pytorch and safetensors are available, download safetensors only - if has_pytorch and has_safetensors: - for i in range(len(classifications)-1, -1, -1): - if classifications[i] == 'pytorch': + if (has_pytorch or has_pt) and has_safetensors: + for i in range(len(classifications) - 1, -1, -1): + if classifications[i] in ['pytorch', 'pt']: links.pop(i) - return links + return links, sha256, is_lora -if __name__ == '__main__': - model = args.MODEL - branch = args.branch - if model is None: - model, branch = select_model_from_default_options() - else: - if model[-1] == '/': - model = model[:-1] - branch = args.branch - if branch is None: - branch = "main" - else: - try: - branch = sanitize_branch_name(branch) - except ValueError as err_branch: - print(f"Error: {err_branch}") - sys.exit() + +def get_output_folder(model, branch, is_lora, base_folder=None): + if base_folder is None: + base_folder = 'models' if not is_lora else 'loras' + + output_folder = f"{'_'.join(model.split('/')[-2:])}" if branch != 'main': - output_folder = Path("models") / (model.split('/')[-1] + f'_{branch}') + output_folder += f'_{branch}' + output_folder = Path(base_folder) / output_folder + return output_folder + + +def get_single_file(url, output_folder, start_from_scratch=False): + filename = Path(url.rsplit('/', 1)[1]) + output_path = output_folder / filename + if output_path.exists() and not start_from_scratch: + # Check if the file has already been downloaded completely + r = requests.get(url, stream=True, timeout=10) + total_size = int(r.headers.get('content-length', 0)) + if output_path.stat().st_size >= total_size: + return + # Otherwise, resume the download from where it left off + headers = {'Range': f'bytes={output_path.stat().st_size}-'} + mode = 'ab' else: - output_folder = Path("models") / model.split('/')[-1] + headers = {} + mode = 'wb' + + r = requests.get(url, stream=True, headers=headers, timeout=10) + with open(output_path, mode) as f: + total_size = int(r.headers.get('content-length', 0)) + block_size = 1024 + with tqdm.tqdm(total=total_size, unit='iB', unit_scale=True, bar_format='{l_bar}{bar}| {n_fmt:6}/{total_fmt:6} {rate_fmt:6}') as t: + for data in r.iter_content(block_size): + t.update(len(data)) + f.write(data) + + +def start_download_threads(file_list, output_folder, start_from_scratch=False, threads=1): + thread_map(lambda url: get_single_file(url, output_folder, start_from_scratch=start_from_scratch), file_list, max_workers=threads, disable=True) + + +def download_model_files(model, branch, links, sha256, output_folder, start_from_scratch=False, threads=1): + # Creating the folder and writing the metadata if not output_folder.exists(): output_folder.mkdir() - - links = get_download_links_from_huggingface(model, branch) + with open(output_folder / 'huggingface-metadata.txt', 'w') as f: + f.write(f'url: https://huggingface.co/{model}\n') + f.write(f'branch: {branch}\n') + f.write(f'download date: {str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))}\n') + sha256_str = '' + for i in range(len(sha256)): + sha256_str += f' {sha256[i][1]} {sha256[i][0]}\n' + if sha256_str != '': + f.write(f'sha256sum:\n{sha256_str}') # Downloading the files print(f"Downloading the model to {output_folder}") - pool = multiprocessing.Pool(processes=args.threads) - results = pool.map(get_file, [[links[i], output_folder, i+1, len(links)] for i in range(len(links))]) - pool.close() - pool.join() + start_download_threads(links, output_folder, start_from_scratch=start_from_scratch, threads=threads) + + +def check_model_files(model, branch, links, sha256, output_folder): + # Validate the checksums + validated = True + for i in range(len(sha256)): + fpath = (output_folder / sha256[i][0]) + + if not fpath.exists(): + print(f"The following file is missing: {fpath}") + validated = False + continue + + with open(output_folder / sha256[i][0], "rb") as f: + bytes = f.read() + file_hash = hashlib.sha256(bytes).hexdigest() + if file_hash != sha256[i][1]: + print(f'Checksum failed: {sha256[i][0]} {sha256[i][1]}') + validated = False + else: + print(f'Checksum validated: {sha256[i][0]} {sha256[i][1]}') + + if validated: + print('[+] Validated checksums of all model files!') + else: + print('[-] Invalid checksums. Rerun download-model.py with the --clean flag.') + + +if __name__ == '__main__': + + parser = argparse.ArgumentParser() + parser.add_argument('MODEL', type=str, default=None, nargs='?') + parser.add_argument('--branch', type=str, default='main', help='Name of the Git branch to download from.') + parser.add_argument('--threads', type=int, default=1, help='Number of files to download simultaneously.') + parser.add_argument('--text-only', action='store_true', help='Only download text files (txt/json).') + parser.add_argument('--output', type=str, default=None, help='The folder where the model should be saved.') + parser.add_argument('--clean', action='store_true', help='Does not resume the previous download.') + parser.add_argument('--check', action='store_true', help='Validates the checksums of model files.') + args = parser.parse_args() + + branch = args.branch + model = args.MODEL + if model is None: + model, branch = select_model_from_default_options() + + # Cleaning up the model/branch names + try: + model, branch = sanitize_model_and_branch_names(model, branch) + except ValueError as err_branch: + print(f"Error: {err_branch}") + sys.exit() + + # Getting the download links from Hugging Face + links, sha256, is_lora = get_download_links_from_huggingface(model, branch, text_only=args.text_only) + + # Getting the output folder + output_folder = get_output_folder(model, branch, is_lora, base_folder=args.output) + + if args.check: + # Check previously downloaded files + check_model_files(model, branch, links, sha256, output_folder) + else: + # Download files + download_model_files(model, branch, links, sha256, output_folder, threads=args.threads) diff --git a/extensions/api/blocking_api.py b/extensions/api/blocking_api.py new file mode 100644 index 0000000000000000000000000000000000000000..134e99d4ccdf00b3ea8cd229e471db59d6d1b73a --- /dev/null +++ b/extensions/api/blocking_api.py @@ -0,0 +1,87 @@ +import json +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from threading import Thread + +from extensions.api.util import build_parameters, try_start_cloudflared +from modules import shared +from modules.text_generation import encode, generate_reply + + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + if self.path == '/api/v1/model': + self.send_response(200) + self.end_headers() + response = json.dumps({ + 'result': shared.model_name + }) + + self.wfile.write(response.encode('utf-8')) + else: + self.send_error(404) + + def do_POST(self): + content_length = int(self.headers['Content-Length']) + body = json.loads(self.rfile.read(content_length).decode('utf-8')) + + if self.path == '/api/v1/generate': + self.send_response(200) + self.send_header('Content-Type', 'application/json') + self.end_headers() + + prompt = body['prompt'] + generate_params = build_parameters(body) + stopping_strings = generate_params.pop('stopping_strings') + generate_params['stream'] = False + + generator = generate_reply( + prompt, generate_params, stopping_strings=stopping_strings, is_chat=False) + + answer = '' + for a in generator: + answer = a + + response = json.dumps({ + 'results': [{ + 'text': answer + }] + }) + self.wfile.write(response.encode('utf-8')) + elif self.path == '/api/v1/token-count': + self.send_response(200) + self.send_header('Content-Type', 'application/json') + self.end_headers() + + tokens = encode(body['prompt'])[0] + response = json.dumps({ + 'results': [{ + 'tokens': len(tokens) + }] + }) + self.wfile.write(response.encode('utf-8')) + else: + self.send_error(404) + + +def _run_server(port: int, share: bool = False): + address = '0.0.0.0' if shared.args.listen else '127.0.0.1' + + server = ThreadingHTTPServer((address, port), Handler) + + def on_start(public_url: str): + print(f'Starting non-streaming server at public url {public_url}/api') + + if share: + try: + try_start_cloudflared(port, max_attempts=3, on_start=on_start) + except Exception: + pass + else: + print( + f'Starting API at http://{address}:{port}/api') + + server.serve_forever() + + +def start_server(port: int, share: bool = False): + Thread(target=_run_server, args=[port, share], daemon=True).start() diff --git a/extensions/api/requirements.txt b/extensions/api/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..14e29d3521915c9fd4fb62385dc971e7a8c4bc83 --- /dev/null +++ b/extensions/api/requirements.txt @@ -0,0 +1,2 @@ +flask_cloudflared==0.0.12 +websockets==11.0.2 \ No newline at end of file diff --git a/extensions/api/script.py b/extensions/api/script.py new file mode 100644 index 0000000000000000000000000000000000000000..5544de725a406c2619e8d465a14f5969f093387e --- /dev/null +++ b/extensions/api/script.py @@ -0,0 +1,7 @@ +import extensions.api.blocking_api as blocking_api +import extensions.api.streaming_api as streaming_api +from modules import shared + +def setup(): + blocking_api.start_server(shared.args.api_blocking_port, share=shared.args.public_api) + streaming_api.start_server(shared.args.api_streaming_port, share=shared.args.public_api) diff --git a/extensions/api/streaming_api.py b/extensions/api/streaming_api.py new file mode 100644 index 0000000000000000000000000000000000000000..e50dfa2266594f9edc7fb2b6f8659f275236279f --- /dev/null +++ b/extensions/api/streaming_api.py @@ -0,0 +1,78 @@ +import asyncio +import json +from threading import Thread + +from websockets.server import serve + +from extensions.api.util import build_parameters, try_start_cloudflared +from modules import shared +from modules.text_generation import generate_reply + +PATH = '/api/v1/stream' + + +async def _handle_connection(websocket, path): + + if path != PATH: + print(f'Streaming api: unknown path: {path}') + return + + async for message in websocket: + message = json.loads(message) + + prompt = message['prompt'] + generate_params = build_parameters(message) + stopping_strings = generate_params.pop('stopping_strings') + generate_params['stream'] = True + + generator = generate_reply( + prompt, generate_params, stopping_strings=stopping_strings, is_chat=False) + + # As we stream, only send the new bytes. + skip_index = 0 + message_num = 0 + + for a in generator: + to_send = a[skip_index:] + await websocket.send(json.dumps({ + 'event': 'text_stream', + 'message_num': message_num, + 'text': to_send + })) + + await asyncio.sleep(0) + + skip_index += len(to_send) + message_num += 1 + + await websocket.send(json.dumps({ + 'event': 'stream_end', + 'message_num': message_num + })) + + +async def _run(host: str, port: int): + async with serve(_handle_connection, host, port, ping_interval=None): + await asyncio.Future() # run forever + + +def _run_server(port: int, share: bool = False): + address = '0.0.0.0' if shared.args.listen else '127.0.0.1' + + def on_start(public_url: str): + public_url = public_url.replace('https://', 'wss://') + print(f'Starting streaming server at public url {public_url}{PATH}') + + if share: + try: + try_start_cloudflared(port, max_attempts=3, on_start=on_start) + except Exception as e: + print(e) + else: + print(f'Starting streaming server at ws://{address}:{port}{PATH}') + + asyncio.run(_run(host=address, port=port)) + + +def start_server(port: int, share: bool = False): + Thread(target=_run_server, args=[port, share], daemon=True).start() diff --git a/extensions/api/util.py b/extensions/api/util.py new file mode 100644 index 0000000000000000000000000000000000000000..e637ac0ec29d8c251952da470b507edf0962180a --- /dev/null +++ b/extensions/api/util.py @@ -0,0 +1,71 @@ +import time +import traceback +from threading import Thread +from typing import Callable, Optional + +from modules.text_generation import get_encoded_length + + +def build_parameters(body): + prompt = body['prompt'] + + prompt_lines = [k.strip() for k in prompt.split('\n')] + max_context = body.get('max_context_length', 2048) + while len(prompt_lines) >= 0 and get_encoded_length('\n'.join(prompt_lines)) > max_context: + prompt_lines.pop(0) + + prompt = '\n'.join(prompt_lines) + + generate_params = { + 'max_new_tokens': int(body.get('max_new_tokens', body.get('max_length', 200))), + 'do_sample': bool(body.get('do_sample', True)), + 'temperature': float(body.get('temperature', 0.5)), + 'top_p': float(body.get('top_p', 1)), + 'typical_p': float(body.get('typical_p', body.get('typical', 1))), + 'repetition_penalty': float(body.get('repetition_penalty', body.get('rep_pen', 1.1))), + 'encoder_repetition_penalty': float(body.get('encoder_repetition_penalty', 1.0)), + 'top_k': int(body.get('top_k', 0)), + 'min_length': int(body.get('min_length', 0)), + 'no_repeat_ngram_size': int(body.get('no_repeat_ngram_size', 0)), + 'num_beams': int(body.get('num_beams', 1)), + 'penalty_alpha': float(body.get('penalty_alpha', 0)), + 'length_penalty': float(body.get('length_penalty', 1)), + 'early_stopping': bool(body.get('early_stopping', False)), + 'seed': int(body.get('seed', -1)), + 'add_bos_token': bool(body.get('add_bos_token', True)), + 'truncation_length': int(body.get('truncation_length', 2048)), + 'ban_eos_token': bool(body.get('ban_eos_token', False)), + 'skip_special_tokens': bool(body.get('skip_special_tokens', True)), + 'custom_stopping_strings': '', # leave this blank + 'stopping_strings': body.get('stopping_strings', []), + } + + return generate_params + + +def try_start_cloudflared(port: int, max_attempts: int = 3, on_start: Optional[Callable[[str], None]] = None): + Thread(target=_start_cloudflared, args=[ + port, max_attempts, on_start], daemon=True).start() + + +def _start_cloudflared(port: int, max_attempts: int = 3, on_start: Optional[Callable[[str], None]] = None): + try: + from flask_cloudflared import _run_cloudflared + except ImportError: + print('You should install flask_cloudflared manually') + raise Exception( + 'flask_cloudflared not installed. Make sure you installed the requirements.txt for this extension.') + + for _ in range(max_attempts): + try: + public_url = _run_cloudflared(port, port + 1) + + if on_start: + on_start(public_url) + + return + except Exception: + traceback.print_exc() + time.sleep(3) + + raise Exception('Could not start cloudflared.') diff --git a/extensions/character_bias/script.py b/extensions/character_bias/script.py index 35b38c0edcb38512f2472937578a363343a4468c..ff12f3afdc28be4ead12ffab90bd9fbd783514a2 100644 --- a/extensions/character_bias/script.py +++ b/extensions/character_bias/script.py @@ -1,42 +1,83 @@ +import os + import gradio as gr +# get the current directory of the script +current_dir = os.path.dirname(os.path.abspath(__file__)) + +# check if the bias_options.txt file exists, if not, create it +bias_file = os.path.join(current_dir, "bias_options.txt") +if not os.path.isfile(bias_file): + with open(bias_file, "w") as f: + f.write("*I am so happy*\n*I am so sad*\n*I am so excited*\n*I am so bored*\n*I am so angry*") + +# read bias options from the text file +with open(bias_file, "r") as f: + bias_options = [line.strip() for line in f.readlines()] + params = { "activate": True, "bias string": " *I am so happy*", + "use custom string": False, } + def input_modifier(string): """ This function is applied to your text inputs before they are fed into the model. - """ - + """ return string + def output_modifier(string): """ This function is applied to the model outputs. """ - return string + def bot_prefix_modifier(string): """ This function is only applied in chat mode. It modifies the prefix text for the Bot and can be used to bias its behavior. """ - - if params['activate'] == True: - return f'{string} {params["bias string"].strip()} ' + if params['activate']: + if params['use custom string']: + return f'{string} {params["custom string"].strip()} ' + else: + return f'{string} {params["bias string"].strip()} ' else: return string + def ui(): # Gradio elements activate = gr.Checkbox(value=params['activate'], label='Activate character bias') - string = gr.Textbox(value=params["bias string"], label='Character bias') + dropdown_string = gr.Dropdown(choices=bias_options, value=params["bias string"], label='Character bias', info='To edit the options in this dropdown edit the "bias_options.txt" file') + use_custom_string = gr.Checkbox(value=False, label='Use custom bias textbox instead of dropdown') + custom_string = gr.Textbox(value="", placeholder="Enter custom bias string", label="Custom Character Bias", info='To use this textbox activate the checkbox above') # Event functions to update the parameters in the backend - string.change(lambda x: params.update({"bias string": x}), string, None) + def update_bias_string(x): + if x: + params.update({"bias string": x}) + else: + params.update({"bias string": dropdown_string.get()}) + return x + + def update_custom_string(x): + params.update({"custom string": x}) + + dropdown_string.change(update_bias_string, dropdown_string, None) + custom_string.change(update_custom_string, custom_string, None) activate.change(lambda x: params.update({"activate": x}), activate, None) + use_custom_string.change(lambda x: params.update({"use custom string": x}), use_custom_string, None) + + # Group elements together depending on the selected option + def bias_string_group(): + if use_custom_string.value: + return gr.Group([use_custom_string, custom_string]) + else: + return dropdown_string diff --git a/extensions/elevenlabs_tts/requirements.txt b/extensions/elevenlabs_tts/requirements.txt index 8ec07a8a7fcf02ca48cc00520e66fcb58c447393..2cfc1960ce2cef55d0f85fb3c88bbb4d28bfcd80 100644 --- a/extensions/elevenlabs_tts/requirements.txt +++ b/extensions/elevenlabs_tts/requirements.txt @@ -1,3 +1 @@ -elevenlabslib -soundfile -sounddevice +elevenlabs==0.2.* diff --git a/extensions/elevenlabs_tts/script.py b/extensions/elevenlabs_tts/script.py index 90d61efc6aa77bc2377c435eefe4cf623b588168..327a9a1192d23847f8b214ca43b447251f928bec 100644 --- a/extensions/elevenlabs_tts/script.py +++ b/extensions/elevenlabs_tts/script.py @@ -1,113 +1,180 @@ +import re from pathlib import Path +import elevenlabs import gradio as gr -from elevenlabslib import * -from elevenlabslib.helpers import * +from modules import chat, shared params = { 'activate': True, - 'api_key': '12345', + 'api_key': None, 'selected_voice': 'None', + 'autoplay': False, + 'show_text': True, } -initial_voice = ['None'] +voices = None wav_idx = 0 -user = ElevenLabsUser(params['api_key']) -user_info = None - - -# Check if the API is valid and refresh the UI accordingly. -def check_valid_api(): - - global user, user_info, params - - user = ElevenLabsUser(params['api_key']) - user_info = user._get_subscription_data() - print('checking api') - if params['activate'] == False: - return gr.update(value='Disconnected') - elif user_info is None: - print('Incorrect API Key') - return gr.update(value='Disconnected') - else: - print('Got an API Key!') - return gr.update(value='Connected') - -# Once the API is verified, get the available voices and update the dropdown list + + +def update_api_key(key): + params['api_key'] = key + if key is not None: + elevenlabs.set_api_key(key) + + def refresh_voices(): - - global user, user_info - - your_voices = [None] - if user_info is not None: - for voice in user.get_available_voices(): - your_voices.append(voice.initialName) - return gr.Dropdown.update(choices=your_voices) - else: - return + global params + your_voices = elevenlabs.voices() + voice_names = [voice.name for voice in your_voices] + return voice_names + + +def refresh_voices_dd(): + all_voices = refresh_voices() + return gr.Dropdown.update(value=all_voices[0], choices=all_voices) + + +def remove_tts_from_history(): + for i, entry in enumerate(shared.history['internal']): + shared.history['visible'][i] = [shared.history['visible'][i][0], entry[1]] + + +def toggle_text_in_history(): + for i, entry in enumerate(shared.history['visible']): + visible_reply = entry[1] + if visible_reply.startswith('')[0]}\n\n{reply}" + ] + else: + shared.history['visible'][i] = [ + shared.history['visible'][i][0], f"{visible_reply.split('')[0]}" + ] + def remove_surrounded_chars(string): - new_string = "" - in_star = False - for char in string: - if char == '*': - in_star = not in_star - elif not in_star: - new_string += char - return new_string + # this expression matches to 'as few symbols as possible (0 upwards) between any asterisks' OR + # 'as few symbols as possible (0 upwards) between an asterisk and the end of the string' + return re.sub('\*[^\*]*?(\*|$)', '', string) + + +def state_modifier(state): + state['stream'] = False + return state + def input_modifier(string): """ This function is applied to your text inputs before they are fed into the model. """ + # Remove autoplay from the last reply + if shared.is_chat() and len(shared.history['internal']) > 0: + shared.history['visible'][-1] = [ + shared.history['visible'][-1][0], + shared.history['visible'][-1][1].replace('controls autoplay>', 'controls>') + ] + + if params['activate']: + shared.processing_message = "*Is recording a voice message...*" return string + def output_modifier(string): """ This function is applied to the model outputs. """ - global params, wav_idx, user, user_info - - if params['activate'] == False: - return string - elif user_info == None: + global params, wav_idx + + if not params['activate']: return string + original_string = string string = remove_surrounded_chars(string) string = string.replace('"', '') string = string.replace('“', '') string = string.replace('\n', ' ') string = string.strip() - if string == '': string = 'empty reply, try regenerating' - - output_file = Path(f'extensions/elevenlabs_tts/outputs/{wav_idx:06d}.wav'.format(wav_idx)) - voice = user.get_voices_by_name(params['selected_voice'])[0] - audio_data = voice.generate_audio_bytes(string) - save_bytes_to_path(Path(f'extensions/elevenlabs_tts/outputs/{wav_idx:06d}.wav'), audio_data) - - string = f'' - wav_idx += 1 + + output_file = Path(f'extensions/elevenlabs_tts/outputs/{wav_idx:06d}.mp3'.format(wav_idx)) + print(f'Outputing audio to {str(output_file)}') + try: + audio = elevenlabs.generate(text=string, voice=params['selected_voice'], model="eleven_monolingual_v1") + elevenlabs.save(audio, str(output_file)) + + autoplay = 'autoplay' if params['autoplay'] else '' + string = f'' + wav_idx += 1 + except elevenlabs.api.error.UnauthenticatedRateLimitError: + string = "🤖 ElevenLabs Unauthenticated Rate Limit Reached - Please create an API key to continue\n\n" + except elevenlabs.api.error.RateLimitError: + string = "🤖 ElevenLabs API Tier Limit Reached\n\n" + except elevenlabs.api.error.APIError as err: + string = f"🤖 ElevenLabs Error: {err}\n\n" + + if params['show_text']: + string += f'\n\n{original_string}' + + shared.processing_message = "*Is typing...*" return string + def ui(): + global voices + if not voices: + voices = refresh_voices() + params['selected_voice'] = voices[0] # Gradio elements with gr.Row(): activate = gr.Checkbox(value=params['activate'], label='Activate TTS') - connection_status = gr.Textbox(value='Disconnected', label='Connection Status') - voice = gr.Dropdown(value=params['selected_voice'], choices=initial_voice, label='TTS Voice') + autoplay = gr.Checkbox(value=params['autoplay'], label='Play TTS automatically') + show_text = gr.Checkbox(value=params['show_text'], label='Show message text under audio player') + + with gr.Row(): + voice = gr.Dropdown(value=params['selected_voice'], choices=voices, label='TTS Voice') + refresh = gr.Button(value='Refresh') + with gr.Row(): api_key = gr.Textbox(placeholder="Enter your API key.", label='API Key') - connect = gr.Button(value='Connect') + + with gr.Row(): + convert = gr.Button('Permanently replace audios with the message texts') + convert_cancel = gr.Button('Cancel', visible=False) + convert_confirm = gr.Button('Confirm (cannot be undone)', variant="stop", visible=False) + + # Convert history with confirmation + convert_arr = [convert_confirm, convert, convert_cancel] + convert.click(lambda: [gr.update(visible=True), gr.update(visible=False), gr.update(visible=True)], None, convert_arr) + convert_confirm.click( + lambda: [gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)], None, convert_arr).then( + remove_tts_from_history, None, None).then( + chat.save_history, shared.gradio['mode'], None, show_progress=False).then( + chat.redraw_html, shared.reload_inputs, shared.gradio['display']) + + convert_cancel.click(lambda: [gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)], None, convert_arr) + + # Toggle message text in history + show_text.change( + lambda x: params.update({"show_text": x}), show_text, None).then( + toggle_text_in_history, None, None).then( + chat.save_history, shared.gradio['mode'], None, show_progress=False).then( + chat.redraw_html, shared.reload_inputs, shared.gradio['display']) + + convert_cancel.click(lambda: [gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)], None, convert_arr) # Event functions to update the parameters in the backend activate.change(lambda x: params.update({'activate': x}), activate, None) voice.change(lambda x: params.update({'selected_voice': x}), voice, None) - api_key.change(lambda x: params.update({'api_key': x}), api_key, None) - connect.click(check_valid_api, [], connection_status) - connect.click(refresh_voices, [], voice) + api_key.change(update_api_key, api_key, None) + # connect.click(check_valid_api, [], connection_status) + refresh.click(refresh_voices_dd, [], voice) + # Event functions to update the parameters in the backend + autoplay.change(lambda x: params.update({"autoplay": x}), autoplay, None) diff --git a/extensions/gallery/script.py b/extensions/gallery/script.py index 8a2d7cf988734a7ab0966d047ff3d31ba58324b7..993ef273839e7cfbf9e80f2d7f9d4a71d208b446 100644 --- a/extensions/gallery/script.py +++ b/extensions/gallery/script.py @@ -3,18 +3,27 @@ from pathlib import Path import gradio as gr from modules.html_generator import get_image_cache +from modules.shared import gradio -def generate_html(): +def generate_css(): css = """ - .character-gallery { + .character-gallery > .gallery { margin: 1rem 0; - display: grid; + display: grid !important; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); grid-column-gap: 0.4rem; grid-row-gap: 1.2rem; } + .character-gallery > .label { + display: none !important; + } + + .character-gallery button.gallery-item { + display: contents; + } + .character-container { cursor: pointer; text-align: center; @@ -45,38 +54,43 @@ def generate_html(): overflow-wrap: anywhere; } """ + return css - container_html = f'