Spaces:
Sleeping
Sleeping
Create app_8bit.py
Browse files- app_8bit.py +98 -0
app_8bit.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Versi贸n con cuantizaci贸n de 8 bits para reducir el uso de memoria.
|
| 3 |
+
Renombra este archivo a app.py para usar esta versi贸n optimizada.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 8 |
+
import torch
|
| 9 |
+
import gc
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
# Funci贸n para cargar el prompt desde el archivo
|
| 13 |
+
def get_system_prompt():
|
| 14 |
+
with open("prompt.txt", "r", encoding="utf-8") as f:
|
| 15 |
+
return f.read().strip()
|
| 16 |
+
|
| 17 |
+
# Funci贸n para generar respuestas
|
| 18 |
+
def generate_response(user_message):
|
| 19 |
+
try:
|
| 20 |
+
if not user_message.strip():
|
| 21 |
+
return "Por favor, escribe una pregunta para que pueda ayudarte."
|
| 22 |
+
|
| 23 |
+
# Obtener el prompt del sistema
|
| 24 |
+
system_prompt = get_system_prompt()
|
| 25 |
+
|
| 26 |
+
# Crear el prompt completo
|
| 27 |
+
prompt = f"{system_prompt}\n\nPregunta: {user_message}\n\nRespuesta:"
|
| 28 |
+
|
| 29 |
+
# Generar respuesta usando el pipeline
|
| 30 |
+
response = generator(
|
| 31 |
+
prompt,
|
| 32 |
+
max_new_tokens=512,
|
| 33 |
+
temperature=0.7,
|
| 34 |
+
top_p=0.9,
|
| 35 |
+
do_sample=True,
|
| 36 |
+
num_return_sequences=1
|
| 37 |
+
)[0]["generated_text"]
|
| 38 |
+
|
| 39 |
+
# Extraer solo la respuesta (despu茅s de "Respuesta:")
|
| 40 |
+
assistant_response = response.split("Respuesta:")[-1].strip()
|
| 41 |
+
|
| 42 |
+
# Forzar recolecci贸n de basura
|
| 43 |
+
gc.collect()
|
| 44 |
+
torch.cuda.empty_cache() if torch.cuda.is_available() else None
|
| 45 |
+
|
| 46 |
+
return assistant_response
|
| 47 |
+
|
| 48 |
+
except Exception as e:
|
| 49 |
+
print(f"Error: {str(e)}")
|
| 50 |
+
return f"Lo siento, ha ocurrido un error: {str(e)}"
|
| 51 |
+
|
| 52 |
+
# Cargar el modelo y crear el pipeline
|
| 53 |
+
print("Cargando modelo Phi-2 con cuantizaci贸n de 8 bits...")
|
| 54 |
+
|
| 55 |
+
# Usar un modelo peque帽o optimizado para espa帽ol
|
| 56 |
+
model_name = "microsoft/phi-2" # Modelo de 2.7B par谩metros, mucho m谩s ligero que 7B
|
| 57 |
+
|
| 58 |
+
# Configuraci贸n para reducir el uso de memoria con cuantizaci贸n de 8 bits
|
| 59 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 60 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 61 |
+
model_name,
|
| 62 |
+
load_in_8bit=True, # Cuantizaci贸n de 8 bits para reducir memoria
|
| 63 |
+
device_map="auto",
|
| 64 |
+
low_cpu_mem_usage=True
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# Crear el pipeline de generaci贸n de texto
|
| 68 |
+
generator = pipeline(
|
| 69 |
+
"text-generation",
|
| 70 |
+
model=model,
|
| 71 |
+
tokenizer=tokenizer
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
print("Modelo cargado correctamente con cuantizaci贸n de 8 bits!")
|
| 75 |
+
|
| 76 |
+
# Crear la interfaz de Gradio
|
| 77 |
+
demo = gr.Interface(
|
| 78 |
+
fn=generate_response,
|
| 79 |
+
inputs=gr.Textbox(
|
| 80 |
+
placeholder="Escribe tu pregunta sobre emprendimiento aqu铆...",
|
| 81 |
+
label="Tu pregunta"
|
| 82 |
+
),
|
| 83 |
+
outputs=gr.Textbox(label="Respuesta de BITER"),
|
| 84 |
+
title="BITER - Tu Mentor en Tiempo Real para Decisiones de Negocio",
|
| 85 |
+
description="BITER es un asistente de IA que responde dudas de emprendedores como si fuera un CEO experimentado.",
|
| 86 |
+
examples=[
|
| 87 |
+
["驴C贸mo puedo validar mi idea de negocio con poco presupuesto?"],
|
| 88 |
+
["驴Cu谩l es la mejor estrategia para conseguir mis primeros clientes?"],
|
| 89 |
+
["驴Deber铆a invertir en publicidad en redes sociales o en SEO?"]
|
| 90 |
+
],
|
| 91 |
+
allow_flagging="never"
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
# Lanzar la aplicaci贸n con configuraci贸n para ahorrar memoria
|
| 95 |
+
if __name__ == "__main__":
|
| 96 |
+
# Configurar menos workers para ahorrar memoria
|
| 97 |
+
demo.queue(max_size=1).launch(share=False, debug=False)
|
| 98 |
+
|