Spaces:
Runtime error
Runtime error
Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162635 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701 unmodified line1721731741751761771781791801811821831841851868 unmodified lines1951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332343 unmodified lines2382392402412422432441 unmodified line2462472482492502512522532542552562572582592602612622632642652662672682692702712722735 unmodified lines2792802812822832842852862872882892902912922932942952962971 unmodified line2993003013023033043053063073082 unmodified lines3113123133143153163175 unmodified lines3233243253263273283291 unmodified line3313323333343353363373383393403413422 unmodified linesimport gradio as grimport torchimport loggingimport sysimport osfrom accelerate import infer_auto_device_map, init_empty_weights# Configure logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# Get HuggingFace token from environment variablehf_token = os.environ.get('HUGGINGFACE_TOKEN')if not hf_token:logger.error("HUGGINGFACE_TOKEN environment variable not set")raise ValueError("Please set the HUGGINGFACE_TOKEN environment variable")# Define the model namemodel_name = "meta-llama/Llama-2-7b-hf"try:logger.info("Starting model initialization...")# Check CUDA availabilitydevice = "cuda" if torch.cuda.is_available() else "cpu"logger.info(f"Using device: {device}")# Configure PyTorch settingsif device == "cuda":torch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = True# Load tokenizerlogger.info("Loading tokenizer...")tokenizer = AutoTokenizer.from_pretrained(model_name,trust_remote_code=True,token=hf_token)tokenizer.pad_token = tokenizer.eos_tokenlogger.info("Tokenizer loaded successfully")# Load model with basic configurationlogger.info("Loading model...")model = AutoModelForCausalLM.from_pretrained(model_name,torch_dtype=torch.float16 if device == "cuda" else torch.float32,trust_remote_code=True,token=hf_token,device_map="auto")logger.info("Model loaded successfully")# Create pipelinelogger.info("Creating generation pipeline...")model_gen = pipeline("text-generation",model=model,5 unmodified linesrepetition_penalty=1.1,device_map="auto")logger.info("Pipeline created successfully")except Exception as e:logger.error(f"Error during initialization: {str(e)}")raise# Configure system messagesystem_message = """You are a helpful AI assistant called AQuaBot. You provide direct, clear, and detailed answers to questions while being aware of environmental impact. Keep your responses natural and informative, but concise. Always provide context and explanations with your answers. Respond directly to questions without using any special tags or markers."""@spaces.GPU(duration=60)@torch.inference_mode()def generate_response(user_input, chat_history):try:logger.info("Generating response for user input...")global total_water_consumption# Calculate water consumption for inputinput_water_consumption = calculate_water_consumption(user_input, True)total_water_consumption += input_water_consumption# Create prompt with Llama 2 chat formatconversation_history = ""if chat_history:for message in chat_history:# Remove any [INST] tags from the historyuser_msg = message[0].replace("[INST]", "").replace("[/INST]", "").strip()assistant_msg = message[1].replace("[INST]", "").replace("[/INST]", "").strip()conversation_history += f"[INST] {user_msg} [/INST] {assistant_msg} "prompt = f"<s>[INST] {system_message}\n\n{conversation_history}[INST] {user_input} [/INST]"logger.info("Generating model response...")outputs = model_gen(prompt,max_new_tokens=256,return_full_text=False,pad_token_id=tokenizer.eos_token_id,do_sample=True,temperature=0.7,top_p=0.9,repetition_penalty=1.1)logger.info("Model response generated successfully")# Clean up the response by removing any [INST] tags and trimmingassistant_response = outputs[0]['generated_text'].strip()assistant_response = assistant_response.replace("[INST]", "").replace("[/INST]", "").strip()# If the response is too short, try to generate a more detailed oneif len(assistant_response.split()) < 10:prompt += "\nPlease provide a more detailed answer with context and explanation."outputs = model_gen(prompt,max_new_tokens=256,return_full_text=False,pad_token_id=tokenizer.eos_token_id,do_sample=True,temperature=0.7,top_p=0.9,repetition_penalty=1.1)assistant_response = outputs[0]['generated_text'].strip()assistant_response = assistant_response.replace("[INST]", "").replace("[/INST]", "").strip()# Calculate water consumption for outputoutput_water_consumption = calculate_water_consumption(assistant_response, False)total_water_consumption += output_water_consumption# Update chat history with the cleaned messageschat_history.append([user_input, assistant_response])# Prepare water consumption messagewater_message = f"""<div style="position: fixed; top: 20px; right: 20px;background-color: white; padding: 15px;border: 2px solid #ff0000; border-radius: 10px;box-shadow: 0 2px 4px rgba(0,0,0,0.1);"><div style="color: #ff0000; font-size: 24px; font-weight: bold;">馃挧 {total_water_consumption:.4f} ml</div><div style="color: #666; font-size: 14px;">Water Consumed</div></div>"""return chat_history, water_messageexcept Exception as e:logger.error(f"Error in generate_response: {str(e)}")error_message = f"An error occurred: {str(e)}"chat_history.append([user_input, error_message])return chat_history, show_water# Constants for water consumption calculationWATER_PER_TOKEN = {"input_training": 0.0000309,"output_training": 0.0000309,1 unmodified line"output_inference": 0.05}# Initialize variablestotal_water_consumption = 0def calculate_tokens(text):try:return len(tokenizer.encode(text))except Exception as e:logger.error(f"Error calculating tokens: {str(e)}")return len(text.split()) + len(text) // 4 # Fallback to approximationdef calculate_water_consumption(text, is_input=True):tokens = calculate_tokens(text)8 unmodified lines@torch.inference_mode()def generate_response(user_input, chat_history):try:logger.info("Generating response for user input...")global total_water_consumption# Calculate water consumption for inputinput_water_consumption = calculate_water_consumption(user_input, True)total_water_consumption += input_water_consumption# Create prompt with Llama 2 chat formatconversation_history = ""if chat_history:for message in chat_history:conversation_history += f"[INST] {message[0]} [/INST] {message[1]} "prompt = f"<s>[INST] {system_message}\n\n{conversation_history}[INST] {user_input} [/INST]"logger.info("Generating model response...")outputs = model_gen(prompt,max_new_tokens=256,return_full_text=False,pad_token_id=tokenizer.eos_token_id,)logger.info("Model response generated successfully")assistant_response = outputs[0]['generated_text'].strip()# Calculate water consumption for outputoutput_water_consumption = calculate_water_consumption(assistant_response, False)total_water_consumption += output_water_consumption# Update chat history with the new formatted messageschat_history.append([user_input, assistant_response])# Prepare water consumption messagewater_message = f"""<div style="position: fixed; top: 20px; right: 20px;background-color: white; padding: 15px;3 unmodified lines馃挧 {total_water_consumption:.4f} ml</div><div style="color: #666; font-size: 14px;">Water Consumed</div></div>"""1 unmodified linereturn chat_history, water_messageexcept Exception as e:logger.error(f"Error in generate_response: {str(e)}")error_message = f"An error occurred: {str(e)}"chat_history.append([user_input, error_message])return chat_history, show_water# Create Gradio interfacetry:logger.info("Creating Gradio interface...")with gr.Blocks(css="div.gradio-container {background-color: #f0f2f6}") as demo:gr.HTML("""<div style="text-align: center; max-width: 800px; margin: 0 auto; padding: 20px;"><h1 style="color: #2d333a;">AQuaBot</h1><p style="color: #4a5568;">Welcome to AQuaBot - An AI assistant that helps raise awarenessabout water consumption in language models.</p></div>""")chatbot = gr.Chatbot()message = gr.Textbox(placeholder="Type your message here...",show_label=False)show_water = gr.HTML(f"""5 unmodified lines馃挧 0.0000 ml</div><div style="color: #666; font-size: 14px;">Water Consumed</div></div>""")clear = gr.Button("Clear Chat")# Add footer with citation and disclaimergr.HTML("""<div style="text-align: center; max-width: 800px; margin: 20px auto; padding: 20px;background-color: #f8f9fa; border-radius: 10px;"><div style="margin-bottom: 15px;"><p style="color: #666; font-size: 14px; font-style: italic;">Water consumption calculations are based on the study:<br>Li, P. et al. (2023). Making AI Less Thirsty: Uncovering and Addressing the Secret WaterFootprint of AI Models. ArXiv Preprint,<a href="https://arxiv.org/abs/2304.03271" target="_blank">https://arxiv.org/abs/2304.03271</a>1 unmodified line</div><div style="border-top: 1px solid #ddd; padding-top: 15px;"><p style="color: #666; font-size: 14px;"><strong>Important note:</strong> This application uses Meta Llama-2-7b modelinstead of GPT-3 for availability and cost reasons. However,the water consumption calculations per token (input/output) are based on theconclusions from the cited paper.</p></div></div>2 unmodified linesdef submit(user_input, chat_history):return generate_response(user_input, chat_history)# Configure event handlersmessage.submit(submit, [message, chatbot], [chatbot, show_water])clear.click(lambda: ([], f"""5 unmodified lines馃挧 0.0000 ml</div><div style="color: #666; font-size: 14px;">Water Consumed</div></div>"""),1 unmodified line[chatbot, show_water])logger.info("Gradio interface created successfully")# Launch the applicationlogger.info("Launching application...")demo.launch()except Exception as e:logger.error(f"Error in Gradio interface creation: {str(e)}")raise2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061625 unmodified lines686970717273747576777879808182838485868788891 unmodified line9192939495969798991001011021031041058 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651663 unmodified lines1701711721731741751761 unmodified line1781791801811821831841851861871881891901911921931941951961971981992002012022032042055 unmodified lines2112122132142152162172182192202212222232242252262272282291 unmodified line2312322332342352362372382392 unmodified lines2422432442452462472485 unmodified lines2542552562572582592601 unmodified line2622632642652662672682692702712722732 unmodified linesimport gradio as grimport torchimport loggingimport osfrom accelerate import infer_auto_device_map, init_empty_weights# Configurar el registrologging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# Obtener el token de HuggingFace desde la variable de entornohf_token = os.environ.get('HUGGINGFACE_TOKEN')if not hf_token:logger.error("La variable de entorno HUGGINGFACE_TOKEN no est谩 configurada")raise ValueError("Por favor, configura la variable de entorno HUGGINGFACE_TOKEN")# Definir el nombre del modelomodel_name = "meta-llama/Llama-2-7b-hf"try:logger.info("Iniciando la inicializaci贸n del modelo...")# Comprobar la disponibilidad de CUDAdevice = "cuda" if torch.cuda.is_available() else "cpu"logger.info(f"Usando el dispositivo: {device}")# Configurar los ajustes de PyTorchif device == "cuda":torch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = True# Cargar el tokenizerlogger.info("Cargando el tokenizer...")tokenizer = AutoTokenizer.from_pretrained(model_name,trust_remote_code=True,use_auth_token=hf_token)tokenizer.pad_token = tokenizer.eos_tokenlogger.info("Tokenizer cargado exitosamente")# Cargar el modelo con la configuraci贸n b谩sicalogger.info("Cargando el modelo...")model = AutoModelForCausalLM.from_pretrained(model_name,torch_dtype=torch.float16 if device == "cuda" else torch.float32,trust_remote_code=True,use_auth_token=hf_token,device_map="auto")logger.info("Modelo cargado exitosamente")# Crear el pipelinelogger.info("Creando el pipeline de generaci贸n...")model_gen = pipeline("text-generation",model=model,5 unmodified linesrepetition_penalty=1.1,device_map="auto")logger.info("Pipeline creado exitosamente")except Exception as e:logger.error(f"Error durante la inicializaci贸n: {str(e)}")raise# Configurar el mensaje del sistemasystem_message = ("You are a helpful AI assistant called AQuaBot. ""You provide direct, clear, and detailed answers to questions while being aware of environmental impact. ""Keep your responses natural and informative, but concise. ""Always provide context and explanations with your answers. ""Respond directly to questions without using any special tags or markers.")# Constantes para el c谩lculo de consumo de aguaWATER_PER_TOKEN = {"input_training": 0.0000309,"output_training": 0.0000309,1 unmodified line"output_inference": 0.05}# Inicializar variablestotal_water_consumption = 0def calculate_tokens(text):try:return len(tokenizer.encode(text))except Exception as e:logger.error(f"Error al calcular los tokens: {str(e)}")return len(text.split()) + len(text) // 4 # Aproximaci贸n en caso de fallodef calculate_water_consumption(text, is_input=True):tokens = calculate_tokens(text)8 unmodified lines@torch.inference_mode()def generate_response(user_input, chat_history):try:logger.info("Generando respuesta para la entrada del usuario...")global total_water_consumption# Calcular el consumo de agua para la entradainput_water_consumption = calculate_water_consumption(user_input, True)total_water_consumption += input_water_consumption# Crear el historial de conversaci贸nconversation_history = ""if chat_history:for message in chat_history:user_msg = message[0].strip()assistant_msg = message[1].strip()conversation_history += f"[INST] {user_msg} [/INST] {assistant_msg} "# Construir el prompt siguiendo el formato correctoprompt = f"[INST] <<SYS>>\n{system_message}\n<</SYS>>\n\n{conversation_history}[INST] {user_input} [/INST]"logger.info("Generando respuesta del modelo...")outputs = model_gen(prompt,max_new_tokens=256,return_full_text=False,pad_token_id=tokenizer.eos_token_id,do_sample=True,temperature=0.7,top_p=0.9,repetition_penalty=1.1)logger.info("Respuesta del modelo generada exitosamente")# Obtener la respuesta del asistente y limpiar etiquetasassistant_response = outputs[0]['generated_text'].strip()# Limpiar las etiquetas [INST] y [/INST]if '[INST]' in assistant_response:assistant_response = assistant_response.split('[/INST]')[-1].strip()assistant_response = assistant_response.replace("[INST]", "").replace("[/INST]", "").strip()# Calcular el consumo de agua para la respuestaoutput_water_consumption = calculate_water_consumption(assistant_response, False)total_water_consumption += output_water_consumption# Actualizar el historial de chatchat_history.append([user_input, assistant_response])# Preparar el mensaje de consumo de aguawater_message = f"""<div style="position: fixed; top: 20px; right: 20px;background-color: white; padding: 15px;3 unmodified lines馃挧 {total_water_consumption:.4f} ml</div><div style="color: #666; font-size: 14px;">Consumo de Agua</div></div>"""1 unmodified linereturn chat_history, water_messageexcept Exception as e:logger.error(f"Error en generate_response: {str(e)}")error_message = f"Ocurri贸 un error: {str(e)}"chat_history.append([user_input, error_message])return chat_history, show_water# Crear la interfaz de Gradiotry:logger.info("Creando la interfaz de Gradio...")with gr.Blocks(css="div.gradio-container {background-color: #f0f2f6}") as demo:gr.HTML("""<div style="text-align: center; max-width: 800px; margin: 0 auto; padding: 20px;"><h1 style="color: #2d333a;">AQuaBot</h1><p style="color: #4a5568;">Bienvenido a AQuaBot - Un asistente de IA que ayuda a concienciarsobre el consumo de agua en los modelos de lenguaje.</p></div>""")chatbot = gr.Chatbot()message = gr.Textbox(placeholder="Escribe tu mensaje aqu铆...",show_label=False)show_water = gr.HTML(f"""5 unmodified lines馃挧 0.0000 ml</div><div style="color: #666; font-size: 14px;">Consumo de Agua</div></div>""")clear = gr.Button("Limpiar Chat")# A帽adir pie de p谩gina con cita y descargo de responsabilidadgr.HTML("""<div style="text-align: center; max-width: 800px; margin: 20px auto; padding: 20px;background-color: #f8f9fa; border-radius: 10px;"><div style="margin-bottom: 15px;"><p style="color: #666; font-size: 14px; font-style: italic;">Los c谩lculos de consumo de agua se basan en el estudio:<br>Li, P. et al. (2023). Making AI Less Thirsty: Uncovering and Addressing the Secret WaterFootprint of AI Models. ArXiv Preprint,<a href="https://arxiv.org/abs/2304.03271" target="_blank">https://arxiv.org/abs/2304.03271</a>1 unmodified line</div><div style="border-top: 1px solid #ddd; padding-top: 15px;"><p style="color: #666; font-size: 14px;"><strong>Nota importante:</strong> Esta aplicaci贸n utiliza el modelo Llama 2 de Meta (7B par谩metros).Los c锟斤拷lculos de consumo de agua por token (entrada/salida) se basan en lasconclusiones generales del art铆culo citado sobre modelos de lenguaje grandes.</p></div></div>2 unmodified linesdef submit(user_input, chat_history):return generate_response(user_input, chat_history)# Configurar los controladores de eventosmessage.submit(submit, [message, chatbot], [chatbot, show_water])clear.click(lambda: ([], f"""5 unmodified lines馃挧 0.0000 ml</div><div style="color: #666; font-size: 14px;">Consumo de Agua</div></div>"""),1 unmodified line[chatbot, show_water])logger.info("Interfaz de Gradio creada exitosamente")# Lanzar la aplicaci贸nlogger.info("Lanzando la aplicaci贸n...")demo.launch()except Exception as e:logger.error(f"Error en la creaci贸n de la interfaz de Gradio: {str(e)}")raise
app.py+78-147