saffr0n's picture
Update app.py
574638c verified
raw
history blame
6.51 kB
import os
from threading import Thread
from typing import Iterator
import gradio as gr
import spaces
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
MAX_MAX_NEW_TOKENS = 1024
DEFAULT_MAX_NEW_TOKENS = 512
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
DESCRIPTION = """\
# Tamil Llama 2
This Space demonstrates the Tamil Llama-2 7b [model](https://huggingface.co/abhinand/tamil-llama-7b-instruct-v0.1) as a daily life AI assistant.
"""
LICENSE = """
<p/>
---
As a derivate work of [Llama-2-7b-chat](https://huggingface.co/meta-llama/Llama-2-7b-chat) by Meta,
this demo is governed by the original [license](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat/blob/main/LICENSE.txt) and [acceptable use policy](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat/blob/main/USE_POLICY.md).
"""
SYSTEM_PROMPT = "ஒரு பணியை எவ்வாறு நிறைவேற்ற வேண்டும் என்று கூறும் அறிவுரை கீழே உள்ளது. வேண்டுகோளைப் பொருத்தமாக நிறைவு செய்கின்ற பதில் ஒன்றை எழுதுக."
PROMPT_TEMPLATE = """{% if messages[0]['role'] == 'system' %}{{ messages[0]['content'] + '\n\n' }}{% endif %}### Instruction:\nநீங்கள் ஒரு பயனருடன் உரையாடும் AI உதவியாளர். இதுவரை உங்கள் தொடர்புகளின் அரட்டை வரலாறு இதுதான்:\n\n{% for message in messages %}{% if message['role'] == 'user' %}{{ '\nUser: ' + message['content'] + '\n'}}{% elif message['role'] == 'assistant' %}{{ '\nAI: ' + message['content'] + '\n'}}{% endif %}{% endfor %}\n\nAI உதவியாளராக, உங்கள் அடுத்த பதிலை அரட்டையில் எழுதவும். ஒரே ஒரு பதிலை மட்டும் எழுதுங்கள்.\n\n### Response:\n"""
if not torch.cuda.is_available():
DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"
if torch.cuda.is_available():
model_id = "abhinand/tamil-llama-7b-instruct-v0.1"
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(model_id)
tokenizer.chat_template = PROMPT_TEMPLATE
tokenizer.use_default_system_prompt = False
@spaces.GPU
def generate(
message: str,
chat_history: list[tuple[str, str]],
system_prompt: str = "",
max_new_tokens: int = 1024,
temperature: float = 0.6,
top_p: float = 0.9,
top_k: int = 50,
repetition_penalty: float = 1.2,
) -> Iterator[str]:
print("chat history: ", chat_history)
conversation = []
if not system_prompt:
system_prompt = SYSTEM_PROMPT
conversation.append({"role": "system", "content": system_prompt})
for user, assistant in chat_history:
conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
conversation.append({"role": "user", "content": message})
print(tokenizer.apply_chat_template(conversation, tokenize=False))
print("conversation: ", conversation)
input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
input_ids = input_ids.to(model.device)
streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
generate_kwargs = dict(
{"input_ids": input_ids},
streamer=streamer,
max_new_tokens=max_new_tokens,
do_sample=True,
top_p=top_p,
top_k=top_k,
temperature=temperature,
num_beams=1,
repetition_penalty=repetition_penalty,
)
t = Thread(target=model.generate, kwargs=generate_kwargs)
t.start()
outputs = []
for text in streamer:
outputs.append(text)
yield "".join(outputs)
chat_interface = gr.ChatInterface(
fn=generate,
fill_height=True,
additional_inputs=[
gr.Textbox(label="System prompt", lines=6),
gr.Slider(
label="Max new tokens",
minimum=1,
maximum=MAX_MAX_NEW_TOKENS,
step=1,
value=DEFAULT_MAX_NEW_TOKENS,
),
gr.Slider(
label="Temperature",
minimum=0.1,
maximum=4.0,
step=0.1,
value=0.6,
),
gr.Slider(
label="Top-p (nucleus sampling)",
minimum=0.05,
maximum=1.0,
step=0.05,
value=0.9,
),
gr.Slider(
label="Top-k",
minimum=1,
maximum=1000,
step=1,
value=50,
),
gr.Slider(
label="Repetition penalty",
minimum=1.0,
maximum=2.0,
step=0.05,
value=1.2,
),
],
stop_btn=None,
examples=[
["நான் எப்படி வேகமாக தூங்க முடியும்?"],
["என் முதலாளி மிகவும் கட்டுப்படுத்துகிறார், நான் என்ன செய்ய வேண்டும்?"],
["திருமணத்திற்கு நான் என்ன அணிய வேண்டும்?"],
["வரலாற்றில் தெரிந்து கொள்ள வேண்டிய சில முக்கியமான காலங்கள் யாவை?"],
["நான் பணம் சம்பாதிக்க வேண்டும் ஆனால் வேடிக்கையாக இருக்க வேண்டும் என்றால் நல்ல தொழில் எது?"],
],
)
with gr.Blocks(css="style.css") as demo:
gr.Markdown(DESCRIPTION)
gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
chat_interface.render()
gr.Markdown(LICENSE)
if __name__ == "__main__":
demo.queue(max_size=20).launch()