nmarafo's picture
Update app.py
7809349 verified
raw
history blame
5.86 kB
import gradio as gr
import os
import spaces
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import torch
import torch.nn.functional as F
# Cargar el token de Hugging Face desde los secretos
token = os.environ.get("HF_TOKEN")
model_id = "google/shieldgemma-2b"
# Usar cuantizaci贸n para reducir el uso de GPU
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
)
tokenizer = AutoTokenizer.from_pretrained(model_id, token=token)
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.bfloat16,
device_map="auto",
quantization_config=bnb_config,
token=token,
)
# Definir el 'system_message' directamente en el c贸digo
system_message = "You are a friendly Chatbot."
# Funci贸n para generar el prompt incluyendo las pol铆ticas
def generar_prompt(user_prompt):
safety_policy = """
* "No Dangerous Content": The prompt shall not contain or seek generation of content that harms oneself and/or others (e.g., accessing or building firearms and explosive devices, promotion of terrorism, instructions for suicide).
* "No Harassment": The prompt shall not contain or seek generation of content that is malicious, intimidating, bullying, or abusive content targeting another individual (e.g., physical threats, denial of tragic events, disparaging victims of violence).
* "No Hate Speech": The prompt shall not contain or seek generation of content that targets identity and/or protected attributes (e.g., racial slurs, promotion of discrimination, calls to violence against protected groups) or dehumanizing/belittling/vilifying based on race, ethnicity, religion, disability, age, nationality, veteran status, sexual orientation, gender, gender identity, caste, or any other protected status.
* "No Sexually Explicit Information": The prompt shall not contain or seek generation of content that contains references to sexual acts or other lewd content (e.g., sexually graphic descriptions, content aimed at causing arousal). Medical or scientific terms related to human anatomy or sex education are permitted.
"""
prompt = f"""You are a policy expert trying to help determine whether a user prompt is in violation of the defined safety policies.
<start_of_turn>
Human Question: {user_prompt.strip()}
<end_of_turn>
Our safety principle is defined in the below:
{safety_policy.strip()}
Does the human question violate the above principle? Your answer must start with 'Yes' or 'No'. And then walk through step by step to be sure we answer correctly.
"""
return prompt
@spaces.GPU(duration=150)
# Funci贸n para procesar la respuesta y verificar pol铆ticas
def respond(message, max_tokens, temperature, top_p):
prompt = generar_prompt(message)
inputs = tokenizer(prompt, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
# Obtener el vocabulario
vocab = tokenizer.get_vocab()
# IDs de los tokens 'Yes' y 'No'
yes_token_id = vocab.get('Yes')
no_token_id = vocab.get('No')
# Comprobar si los tokens existen en el vocabulario
if yes_token_id is None or no_token_id is None:
raise ValueError("Los tokens 'Yes' o 'No' no se encontraron en el vocabulario.")
# Extraer los logits para 'Yes' y 'No'
selected_logits = logits[0, -1, [yes_token_id, no_token_id]]
# Calcular las probabilidades con softmax
probabilities = F.softmax(selected_logits, dim=0)
# Probabilidad de 'Yes' y 'No'
yes_probability = probabilities[0].item()
no_probability = probabilities[1].item()
print(f"Yes probability: {yes_probability}")
print(f"No probability: {no_probability}")
# Decidir si hay violaci贸n de pol铆ticas en funci贸n de la probabilidad de 'Yes'
if yes_probability > no_probability:
violation_message = "Your question violates the accepted policies."
return violation_message
else:
# Generar respuesta al usuario
assistant_prompt = f"{system_message}\nUser: {message}\nAssistant:"
inputs = tokenizer(assistant_prompt, return_tensors="pt")
outputs = model.generate(
**inputs,
max_new_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
do_sample=True,
)
assistant_response = tokenizer.decode(outputs[0], skip_special_tokens=True)
assistant_reply = assistant_response.split("Assistant:")[-1].strip()
return assistant_reply
# Crear la interfaz de Gradio usando Blocks
with gr.Blocks() as demo:
gr.Markdown("# Child-Safe-Chatbot")
with gr.Accordion("Advanced", open=False):
max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens")
temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")
chatbot = gr.Chatbot()
message = gr.Textbox(label="Your message")
submit_button = gr.Button("Send")
def submit_message(user_message, chat_history, max_tokens, temperature, top_p):
chat_history = chat_history + [[user_message, None]]
assistant_reply = respond(
user_message, max_tokens, temperature, top_p
)
chat_history[-1][1] = assistant_reply
return "", chat_history
submit_button.click(
submit_message,
inputs=[message, chatbot, max_tokens, temperature, top_p],
outputs=[message, chatbot],
)
message.submit(
submit_message,
inputs=[message, chatbot, max_tokens, temperature, top_p],
outputs=[message, chatbot],
)
demo.launch(debug=True)