Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -1,57 +1,65 @@
|
|
1 |
import streamlit as st
|
2 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
3 |
import torch
|
|
|
|
|
4 |
|
5 |
-
|
6 |
-
|
7 |
-
if
|
8 |
-
|
9 |
-
|
10 |
-
"Nombre GPU": torch.cuda.get_device_name(0),
|
11 |
-
"Memoria Total (GB)": round(torch.cuda.get_device_properties(0).total_memory/1e9, 2),
|
12 |
-
"CUDA Version": torch.version.cuda
|
13 |
-
}
|
14 |
-
return gpu_info
|
15 |
-
return {"GPU Disponible": False}
|
16 |
-
|
17 |
-
# Configurar autenticación
|
18 |
-
def setup_auth():
|
19 |
-
if 'HUGGINGFACE_TOKEN' in st.secrets:
|
20 |
-
login(st.secrets['HUGGINGFACE_TOKEN'])
|
21 |
return True
|
22 |
else:
|
23 |
-
st.error("No se encontró el token de
|
24 |
st.stop()
|
25 |
return False
|
26 |
|
27 |
-
class
|
28 |
def __init__(self):
|
29 |
-
|
|
|
|
|
|
|
|
|
30 |
self._model = None
|
31 |
self._tokenizer = None
|
32 |
|
33 |
@property
|
34 |
def model(self):
|
35 |
if self._model is None:
|
36 |
-
|
37 |
-
self.
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
return self._model
|
43 |
|
44 |
@property
|
45 |
def tokenizer(self):
|
46 |
if self._tokenizer is None:
|
47 |
-
|
48 |
-
self.
|
49 |
-
|
50 |
-
|
|
|
|
|
|
|
|
|
51 |
return self._tokenizer
|
52 |
|
53 |
def generate_response(self, prompt: str, max_new_tokens: int = 512) -> str:
|
54 |
-
|
|
|
|
|
|
|
55 |
|
56 |
inputs = self.tokenizer(formatted_prompt, return_tensors="pt").to(self.model.device)
|
57 |
|
@@ -62,77 +70,81 @@ class LlamaDemo:
|
|
62 |
num_return_sequences=1,
|
63 |
temperature=0.7,
|
64 |
do_sample=True,
|
65 |
-
top_p=0.9
|
66 |
-
pad_token_id=self.tokenizer.eos_token_id
|
67 |
)
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
|
72 |
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
73 |
-
|
|
|
74 |
|
75 |
def main():
|
76 |
-
st.set_page_config(
|
77 |
-
page_title="Llama 2 Chat Demo",
|
78 |
-
page_icon="🦙",
|
79 |
-
layout="wide"
|
80 |
-
)
|
81 |
|
82 |
-
st.title("🦙 Llama 2 Chat
|
83 |
|
84 |
-
#
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
st.write(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
-
#
|
91 |
if 'llama' not in st.session_state:
|
92 |
-
with st.spinner("
|
93 |
-
|
|
|
|
|
|
|
|
|
94 |
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
# Chat interface
|
99 |
-
with st.container():
|
100 |
-
for message in st.session_state.chat_history:
|
101 |
-
with st.chat_message(message["role"]):
|
102 |
-
st.write(message["content"])
|
103 |
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
})
|
109 |
-
|
110 |
-
with st.chat_message("user"):
|
111 |
-
st.write(prompt)
|
112 |
-
|
113 |
-
with st.chat_message("assistant"):
|
114 |
-
with st.spinner("Thinking..."):
|
115 |
-
try:
|
116 |
-
response = st.session_state.llama.generate_response(prompt)
|
117 |
-
st.write(response)
|
118 |
-
st.session_state.chat_history.append({
|
119 |
-
"role": "assistant",
|
120 |
-
"content": response
|
121 |
-
})
|
122 |
-
except Exception as e:
|
123 |
-
st.error(f"Error: {str(e)}")
|
124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
with st.sidebar:
|
126 |
st.markdown("""
|
127 |
-
###
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
-
|
|
|
|
|
132 |
""")
|
133 |
|
134 |
-
if st.button("
|
135 |
-
st.session_state.
|
136 |
st.experimental_rerun()
|
137 |
|
138 |
if __name__ == "__main__":
|
|
|
1 |
import streamlit as st
|
2 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
3 |
import torch
|
4 |
+
from huggingface_hub import login
|
5 |
+
import os
|
6 |
|
7 |
+
def setup_llama3_auth():
|
8 |
+
"""Configurar autenticación para Llama 3"""
|
9 |
+
if 'HUGGING_FACE_TOKEN_3' in st.secrets:
|
10 |
+
token = st.secrets['HUGGING_FACE_TOKEN_3']
|
11 |
+
login(token)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
return True
|
13 |
else:
|
14 |
+
st.error("No se encontró el token de Llama 3 en los secrets")
|
15 |
st.stop()
|
16 |
return False
|
17 |
|
18 |
+
class Llama3Demo:
|
19 |
def __init__(self):
|
20 |
+
# Verificar autenticación antes de cargar el modelo
|
21 |
+
setup_llama3_auth()
|
22 |
+
|
23 |
+
# Usando el modelo de 3B con instrucciones
|
24 |
+
self.model_name = "meta-llama/Llama-3.2-3B-Instruct"
|
25 |
self._model = None
|
26 |
self._tokenizer = None
|
27 |
|
28 |
@property
|
29 |
def model(self):
|
30 |
if self._model is None:
|
31 |
+
try:
|
32 |
+
self._model = AutoModelForCausalLM.from_pretrained(
|
33 |
+
self.model_name,
|
34 |
+
torch_dtype=torch.float16,
|
35 |
+
device_map="auto",
|
36 |
+
load_in_8bit=True, # Optimización de memoria
|
37 |
+
use_auth_token=st.secrets['HUGGING_FACE_TOKEN_3']
|
38 |
+
)
|
39 |
+
except Exception as e:
|
40 |
+
st.error(f"Error cargando el modelo: {str(e)}")
|
41 |
+
st.error("Verifica tu acceso a Llama 3.2 en https://huggingface.co/meta-llama")
|
42 |
+
raise e
|
43 |
return self._model
|
44 |
|
45 |
@property
|
46 |
def tokenizer(self):
|
47 |
if self._tokenizer is None:
|
48 |
+
try:
|
49 |
+
self._tokenizer = AutoTokenizer.from_pretrained(
|
50 |
+
self.model_name,
|
51 |
+
use_auth_token=st.secrets['HUGGING_FACE_TOKEN_3']
|
52 |
+
)
|
53 |
+
except Exception as e:
|
54 |
+
st.error(f"Error cargando el tokenizer: {str(e)}")
|
55 |
+
raise e
|
56 |
return self._tokenizer
|
57 |
|
58 |
def generate_response(self, prompt: str, max_new_tokens: int = 512) -> str:
|
59 |
+
# Formato específico para Llama 3.2
|
60 |
+
formatted_prompt = f"""<|system|>You are a helpful AI assistant.</s>
|
61 |
+
<|user|>{prompt}</s>
|
62 |
+
<|assistant|>"""
|
63 |
|
64 |
inputs = self.tokenizer(formatted_prompt, return_tensors="pt").to(self.model.device)
|
65 |
|
|
|
70 |
num_return_sequences=1,
|
71 |
temperature=0.7,
|
72 |
do_sample=True,
|
73 |
+
top_p=0.9
|
|
|
74 |
)
|
75 |
+
|
76 |
+
# Limpiar memoria GPU
|
77 |
+
torch.cuda.empty_cache()
|
78 |
|
79 |
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
80 |
+
# Extraer solo la respuesta del asistente
|
81 |
+
return response.split("<|assistant|>")[-1].strip()
|
82 |
|
83 |
def main():
|
84 |
+
st.set_page_config(page_title="Llama 3.2 Chat", page_icon="🦙")
|
|
|
|
|
|
|
|
|
85 |
|
86 |
+
st.title("🦙 Llama 3.2 Chat")
|
87 |
|
88 |
+
# Verificar configuración
|
89 |
+
with st.expander("🔧 Status", expanded=True):
|
90 |
+
try:
|
91 |
+
token_status = setup_llama3_auth()
|
92 |
+
st.write("Token Llama 3:", "✅" if token_status else "❌")
|
93 |
+
|
94 |
+
if torch.cuda.is_available():
|
95 |
+
st.write("GPU:", torch.cuda.get_device_name(0))
|
96 |
+
st.write("Memoria GPU:", f"{torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
|
97 |
+
else:
|
98 |
+
st.warning("GPU no disponible")
|
99 |
+
except Exception as e:
|
100 |
+
st.error(f"Error en configuración: {str(e)}")
|
101 |
|
102 |
+
# Inicializar el modelo
|
103 |
if 'llama' not in st.session_state:
|
104 |
+
with st.spinner("Inicializando Llama 3.2... esto puede tomar unos minutos..."):
|
105 |
+
try:
|
106 |
+
st.session_state.llama = Llama3Demo()
|
107 |
+
except Exception as e:
|
108 |
+
st.error("Error inicializando el modelo")
|
109 |
+
st.stop()
|
110 |
|
111 |
+
# Gestión del historial de chat
|
112 |
+
if 'messages' not in st.session_state:
|
113 |
+
st.session_state.messages = []
|
|
|
|
|
|
|
|
|
|
|
114 |
|
115 |
+
# Mostrar historial
|
116 |
+
for message in st.session_state.messages:
|
117 |
+
with st.chat_message(message["role"]):
|
118 |
+
st.markdown(message["content"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
|
120 |
+
# Interface de chat
|
121 |
+
if prompt := st.chat_input("Escribe tu mensaje aquí"):
|
122 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
123 |
+
with st.chat_message("user"):
|
124 |
+
st.markdown(prompt)
|
125 |
+
|
126 |
+
with st.chat_message("assistant"):
|
127 |
+
try:
|
128 |
+
response = st.session_state.llama.generate_response(prompt)
|
129 |
+
st.markdown(response)
|
130 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
131 |
+
except Exception as e:
|
132 |
+
st.error(f"Error generando respuesta: {str(e)}")
|
133 |
+
|
134 |
+
# Sidebar con información y controles
|
135 |
with st.sidebar:
|
136 |
st.markdown("""
|
137 |
+
### Acerca de
|
138 |
+
Este demo usa Llama 3.2-3B-Instruct, el nuevo modelo de Meta.
|
139 |
+
|
140 |
+
### Características
|
141 |
+
- Modelo de 3B parámetros
|
142 |
+
- Optimizado para diálogo
|
143 |
+
- Cuantización de 8-bits
|
144 |
""")
|
145 |
|
146 |
+
if st.button("Limpiar Chat"):
|
147 |
+
st.session_state.messages = []
|
148 |
st.experimental_rerun()
|
149 |
|
150 |
if __name__ == "__main__":
|