AIdeaText commited on
Commit
24c7e03
·
verified ·
1 Parent(s): a7492f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -85
app.py CHANGED
@@ -1,57 +1,65 @@
1
  import streamlit as st
2
  from transformers import AutoTokenizer, AutoModelForCausalLM
3
  import torch
 
 
4
 
5
- # Verificar GPU al inicio
6
- def check_gpu():
7
- if torch.cuda.is_available():
8
- gpu_info = {
9
- "GPU Disponible": True,
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 Hugging Face en los secrets")
24
  st.stop()
25
  return False
26
 
27
- class LlamaDemo:
28
  def __init__(self):
29
- self.model_name = "meta-llama/Llama-2-7b-chat"
 
 
 
 
30
  self._model = None
31
  self._tokenizer = None
32
 
33
  @property
34
  def model(self):
35
  if self._model is None:
36
- self._model = AutoModelForCausalLM.from_pretrained(
37
- self.model_name,
38
- torch_dtype=torch.float16, # Usar float16 para optimizar memoria
39
- device_map="auto",
40
- load_in_8bit=True # Cuantización 8-bit para optimizar memoria
41
- )
 
 
 
 
 
 
42
  return self._model
43
 
44
  @property
45
  def tokenizer(self):
46
  if self._tokenizer is None:
47
- self._tokenizer = AutoTokenizer.from_pretrained(
48
- self.model_name,
49
- trust_remote_code=True
50
- )
 
 
 
 
51
  return self._tokenizer
52
 
53
  def generate_response(self, prompt: str, max_new_tokens: int = 512) -> str:
54
- formatted_prompt = f"[INST] {prompt} [/INST]"
 
 
 
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
- # Liberar memoria GPU después de generar
70
- torch.cuda.empty_cache()
71
 
72
  response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
73
- return response.split("[/INST]")[-1].strip()
 
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 Demo")
83
 
84
- # Mostrar información de GPU
85
- gpu_info = check_gpu()
86
- with st.expander("💻 GPU Info", expanded=False):
87
- for key, value in gpu_info.items():
88
- st.write(f"{key}: {value}")
 
 
 
 
 
 
 
 
89
 
90
- # Initialize model
91
  if 'llama' not in st.session_state:
92
- with st.spinner("Loading Llama 2... This might take a few minutes..."):
93
- st.session_state.llama = LlamaDemo()
 
 
 
 
94
 
95
- if 'chat_history' not in st.session_state:
96
- st.session_state.chat_history = []
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
- if prompt := st.chat_input("What would you like to discuss?"):
105
- st.session_state.chat_history.append({
106
- "role": "user",
107
- "content": prompt
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
- ### Memory Management
128
- To optimize GPU usage and costs:
129
- - Model runs in 8-bit precision
130
- - Memory is cleared after each generation
131
- - Space sleeps after inactivity
 
 
132
  """)
133
 
134
- if st.button("Clear Chat History"):
135
- st.session_state.chat_history = []
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__":