File size: 5,314 Bytes
f995cde
a16e1cf
f995cde
24c7e03
 
1aaec00
24c7e03
 
 
 
 
5d15c3d
 
24c7e03
5d15c3d
 
 
24c7e03
f995cde
24c7e03
 
 
 
 
1aaec00
 
f995cde
 
1aaec00
 
24c7e03
 
 
 
 
 
 
 
 
 
 
 
1aaec00
 
 
 
 
24c7e03
 
 
 
 
 
 
 
1aaec00
f995cde
1aaec00
24c7e03
 
 
 
fa0a856
1aaec00
 
 
 
 
 
 
 
 
24c7e03
1aaec00
24c7e03
 
 
a16e1cf
1aaec00
24c7e03
 
f995cde
 
24c7e03
f995cde
24c7e03
f995cde
24c7e03
 
 
 
 
 
 
 
 
 
 
 
 
1aaec00
24c7e03
f995cde
24c7e03
 
 
 
 
 
f995cde
24c7e03
 
 
f995cde
24c7e03
 
 
 
f995cde
24c7e03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f995cde
a16e1cf
24c7e03
 
 
 
 
 
 
a16e1cf
 
24c7e03
 
f995cde
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import streamlit as st
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
from huggingface_hub import login
import os

def setup_llama3_auth():
    """Configurar autenticación para Llama 3"""
    if 'HUGGING_FACE_TOKEN_3' in st.secrets:
        token = st.secrets['HUGGING_FACE_TOKEN_3']
        login(token)
        return True
    else:
        st.error("No se encontró el token de Llama 3 en los secrets")
        st.stop()
        return False

class Llama3Demo:
    def __init__(self):
        # Verificar autenticación antes de cargar el modelo
        setup_llama3_auth()
        
        # Usando el modelo de 3B con instrucciones
        self.model_name = "meta-llama/Llama-3.2-3B-Instruct"
        self._model = None
        self._tokenizer = None
        
    @property
    def model(self):
        if self._model is None:
            try:
                self._model = AutoModelForCausalLM.from_pretrained(
                    self.model_name,
                    torch_dtype=torch.float16,
                    device_map="auto",
                    load_in_8bit=True,  # Optimización de memoria
                    use_auth_token=st.secrets['HUGGING_FACE_TOKEN_3']
                )
            except Exception as e:
                st.error(f"Error cargando el modelo: {str(e)}")
                st.error("Verifica tu acceso a Llama 3.2 en https://huggingface.co/meta-llama")
                raise e
        return self._model
    
    @property
    def tokenizer(self):
        if self._tokenizer is None:
            try:
                self._tokenizer = AutoTokenizer.from_pretrained(
                    self.model_name,
                    use_auth_token=st.secrets['HUGGING_FACE_TOKEN_3']
                )
            except Exception as e:
                st.error(f"Error cargando el tokenizer: {str(e)}")
                raise e
        return self._tokenizer

    def generate_response(self, prompt: str, max_new_tokens: int = 512) -> str:
        # Formato específico para Llama 3.2
        formatted_prompt = f"""<|system|>You are a helpful AI assistant.</s>
<|user|>{prompt}</s>
<|assistant|>"""
        
        inputs = self.tokenizer(formatted_prompt, return_tensors="pt").to(self.model.device)
        
        with torch.no_grad():
            outputs = self.model.generate(
                **inputs,
                max_new_tokens=max_new_tokens,
                num_return_sequences=1,
                temperature=0.7,
                do_sample=True,
                top_p=0.9
            )
            
            # Limpiar memoria GPU
            torch.cuda.empty_cache()
        
        response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
        # Extraer solo la respuesta del asistente
        return response.split("<|assistant|>")[-1].strip()

def main():
    st.set_page_config(page_title="Llama 3.2 Chat", page_icon="🦙")
    
    st.title("🦙 Llama 3.2 Chat")
    
    # Verificar configuración
    with st.expander("🔧 Status", expanded=True):
        try:
            token_status = setup_llama3_auth()
            st.write("Token Llama 3:", "✅" if token_status else "❌")
            
            if torch.cuda.is_available():
                st.write("GPU:", torch.cuda.get_device_name(0))
                st.write("Memoria GPU:", f"{torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
            else:
                st.warning("GPU no disponible")
        except Exception as e:
            st.error(f"Error en configuración: {str(e)}")
    
    # Inicializar el modelo
    if 'llama' not in st.session_state:
        with st.spinner("Inicializando Llama 3.2... esto puede tomar unos minutos..."):
            try:
                st.session_state.llama = Llama3Demo()
            except Exception as e:
                st.error("Error inicializando el modelo")
                st.stop()
    
    # Gestión del historial de chat
    if 'messages' not in st.session_state:
        st.session_state.messages = []
    
    # Mostrar historial
    for message in st.session_state.messages:
        with st.chat_message(message["role"]):
            st.markdown(message["content"])
    
    # Interface de chat
    if prompt := st.chat_input("Escribe tu mensaje aquí"):
        st.session_state.messages.append({"role": "user", "content": prompt})
        with st.chat_message("user"):
            st.markdown(prompt)

        with st.chat_message("assistant"):
            try:
                response = st.session_state.llama.generate_response(prompt)
                st.markdown(response)
                st.session_state.messages.append({"role": "assistant", "content": response})
            except Exception as e:
                st.error(f"Error generando respuesta: {str(e)}")
    
    # Sidebar con información y controles
    with st.sidebar:
        st.markdown("""
        ### Acerca de
        Este demo usa Llama 3.2-3B-Instruct, el nuevo modelo de Meta.
        
        ### Características
        - Modelo de 3B parámetros
        - Optimizado para diálogo
        - Cuantización de 8-bits
        """)
        
        if st.button("Limpiar Chat"):
            st.session_state.messages = []
            st.experimental_rerun()

if __name__ == "__main__":
    main()