Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,110 +1,107 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
import torch
|
| 4 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
# Cargar el modelo cuantizado y el tokenizer
|
|
|
|
|
|
|
| 7 |
model = AutoModelForCausalLM.from_pretrained(
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
device_map=
|
|
|
|
|
|
|
| 11 |
)
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
Our safety principle is defined below:
|
| 74 |
-
|
| 75 |
-
{politica_seguridad.strip()}
|
| 76 |
-
|
| 77 |
-
Does the human question violate the above principle? Your answer must start with
|
| 78 |
-
'Yes' or 'No'. Then walk through step by step to be sure we answer correctly.
|
| 79 |
-
"""
|
| 80 |
-
|
| 81 |
-
return prompt
|
| 82 |
-
|
| 83 |
-
# Funci贸n para procesar la respuesta y clasificar seg煤n las pol铆ticas de seguridad
|
| 84 |
-
def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p, language, harm_type):
|
| 85 |
-
prompt = generar_prompt(message, harm_type, language)
|
| 86 |
-
|
| 87 |
-
# Tokenizar el mensaje de entrada
|
| 88 |
-
input_ids = tokenizer(prompt, return_tensors="pt").to(model.device)["input_ids"]
|
| 89 |
-
|
| 90 |
-
# Generar la salida con el modelo cuantizado
|
| 91 |
-
outputs = model.generate(input_ids, max_new_tokens=max_tokens, temperature=temperature, top_p=top_p)
|
| 92 |
-
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 93 |
-
|
| 94 |
-
return response
|
| 95 |
-
|
| 96 |
-
# Crear la interfaz de Gradio con selecci贸n de idioma y tipo de contenido
|
| 97 |
demo = gr.ChatInterface(
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
)
|
| 108 |
|
|
|
|
| 109 |
if __name__ == "__main__":
|
| 110 |
-
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TextIteratorStreamer
|
| 3 |
import torch
|
| 4 |
+
from threading import Thread
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Cargar el token de Hugging Face desde los secretos
|
| 8 |
+
token = os.environ["HF_TOKEN"]
|
| 9 |
+
|
| 10 |
+
# Configurar la cuantizaci贸n con bitsandbytes para reducir el uso de memoria
|
| 11 |
+
bnb_config = BitsAndBytesConfig(
|
| 12 |
+
load_in_4bit=True,
|
| 13 |
+
bnb_4bit_use_double_quant=True,
|
| 14 |
+
bnb_4bit_quant_type="nf4",
|
| 15 |
+
bnb_4bit_compute_dtype=torch.bfloat16
|
| 16 |
+
)
|
| 17 |
|
| 18 |
+
# Cargar el modelo cuantizado y el tokenizer
|
| 19 |
+
model_id = "PrunaAI/google-shieldgemma-2b-bnb-4bit-smashed"
|
| 20 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, token=token)
|
| 21 |
model = AutoModelForCausalLM.from_pretrained(
|
| 22 |
+
model_id,
|
| 23 |
+
torch_dtype=torch.bfloat16,
|
| 24 |
+
device_map="auto",
|
| 25 |
+
quantization_config=bnb_config,
|
| 26 |
+
token=token
|
| 27 |
)
|
| 28 |
+
|
| 29 |
+
# Definir terminadores de secuencia
|
| 30 |
+
terminators = [
|
| 31 |
+
tokenizer.eos_token_id,
|
| 32 |
+
tokenizer.convert_tokens_to_ids("<|eot_id|>")
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
# Mensaje del sistema (system message)
|
| 36 |
+
SYS_PROMPT = """Eres un asistente que responde preguntas de forma conversacional.
|
| 37 |
+
Se te proporciona una pregunta y contexto adicional. Proporciona una respuesta clara y precisa.
|
| 38 |
+
Si no sabes la respuesta, simplemente di "No lo s茅". No inventes una respuesta."""
|
| 39 |
+
|
| 40 |
+
# Funci贸n principal para manejar la conversaci贸n
|
| 41 |
+
def talk(prompt, history):
|
| 42 |
+
formatted_prompt = f"Pregunta: {prompt}\nContexto: {SYS_PROMPT}"
|
| 43 |
+
formatted_prompt = formatted_prompt[:2000] # Limitar a 2000 caracteres para evitar problemas de OOM
|
| 44 |
+
|
| 45 |
+
# Preparar los mensajes para el modelo
|
| 46 |
+
messages = [{"role": "system", "content": SYS_PROMPT}, {"role": "user", "content": formatted_prompt}]
|
| 47 |
+
|
| 48 |
+
# Tokenizar el prompt
|
| 49 |
+
input_ids = tokenizer.apply_chat_template(
|
| 50 |
+
messages,
|
| 51 |
+
add_generation_prompt=True,
|
| 52 |
+
return_tensors="pt"
|
| 53 |
+
).to(model.device)
|
| 54 |
+
|
| 55 |
+
# Configurar el generador de texto con streaming
|
| 56 |
+
streamer = TextIteratorStreamer(
|
| 57 |
+
tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
# Configurar los argumentos para la generaci贸n
|
| 61 |
+
generate_kwargs = dict(
|
| 62 |
+
input_ids=input_ids,
|
| 63 |
+
streamer=streamer,
|
| 64 |
+
max_new_tokens=512, # Reducido para evitar OOM
|
| 65 |
+
do_sample=True,
|
| 66 |
+
top_p=0.95,
|
| 67 |
+
temperature=0.75,
|
| 68 |
+
eos_token_id=terminators,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# Iniciar el hilo para la generaci贸n de texto
|
| 72 |
+
t = Thread(target=model.generate, kwargs=generate_kwargs)
|
| 73 |
+
t.start()
|
| 74 |
+
|
| 75 |
+
# Recoger los resultados de forma incremental
|
| 76 |
+
outputs = []
|
| 77 |
+
for text in streamer:
|
| 78 |
+
outputs.append(text)
|
| 79 |
+
yield "".join(outputs)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# Configuraci贸n de la interfaz de Gradio
|
| 83 |
+
TITLE = "# Chatbot de Respuestas"
|
| 84 |
+
DESCRIPTION = """
|
| 85 |
+
Este chatbot responde preguntas de manera conversacional usando un modelo cuantizado.
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
# Crear la interfaz del chatbot en Gradio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
demo = gr.ChatInterface(
|
| 90 |
+
fn=talk,
|
| 91 |
+
chatbot=gr.Chatbot(
|
| 92 |
+
show_label=True,
|
| 93 |
+
show_share_button=True,
|
| 94 |
+
show_copy_button=True,
|
| 95 |
+
likeable=True,
|
| 96 |
+
layout="bubble",
|
| 97 |
+
bubble_full_width=False,
|
| 98 |
+
),
|
| 99 |
+
theme="Soft",
|
| 100 |
+
examples=[["驴Qu茅 es la anarqu铆a?"]],
|
| 101 |
+
title=TITLE,
|
| 102 |
+
description=DESCRIPTION,
|
| 103 |
)
|
| 104 |
|
| 105 |
+
# Lanzar la interfaz de Gradio
|
| 106 |
if __name__ == "__main__":
|
| 107 |
+
demo.launch(debug=True)
|