Delta0723 commited on
Commit
0b53ce7
·
verified ·
1 Parent(s): b25d0f1

Delete inference_techmind.py

Browse files
Files changed (1) hide show
  1. inference_techmind.py +0 -245
inference_techmind.py DELETED
@@ -1,245 +0,0 @@
1
- """
2
- TechMind PRO - Script de Inferencia Optimizado
3
- Para usar después del entrenamiento
4
- """
5
-
6
- import torch
7
- from transformers import AutoTokenizer, AutoModelForCausalLM
8
- from peft import PeftModel
9
- import time
10
-
11
- # =========================================================
12
- # CONFIGURACIÓN
13
- # =========================================================
14
- BASE_MODEL = "EleutherAI/gpt-j-6B"
15
- LORA_PATH = "/workspace/TechMind/lora_final_pro" # Modelo de FASE 2
16
-
17
- SYSTEM_PROMPT = (
18
- "Eres TechMind, experto en redes y ciberseguridad. "
19
- "Responde SIEMPRE en español claro y técnico, con pasos y comandos cuando aplique.\n"
20
- )
21
-
22
- # =========================================================
23
- # CARGAR MODELO (solo una vez)
24
- # =========================================================
25
- print("🧩 Cargando TechMind PRO...")
26
- print(f"📁 Modelo: {LORA_PATH}")
27
-
28
- tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
29
- if tokenizer.pad_token is None:
30
- tokenizer.pad_token = tokenizer.eos_token
31
-
32
- print("🔧 Cargando GPT-J 6B...")
33
- model = AutoModelForCausalLM.from_pretrained(
34
- BASE_MODEL,
35
- torch_dtype=torch.float16,
36
- device_map="auto",
37
- load_in_8bit=True # Reduce RAM
38
- )
39
-
40
- print("🔗 Aplicando LoRA...")
41
- model = PeftModel.from_pretrained(model, LORA_PATH)
42
- model.eval()
43
-
44
- print("✅ TechMind PRO listo\n")
45
-
46
- # =========================================================
47
- # FUNCIÓN DE INFERENCIA
48
- # =========================================================
49
- def ask_techmind(
50
- pregunta: str,
51
- max_tokens: int = 400,
52
- temperature: float = 0.6,
53
- top_p: float = 0.9
54
- ) -> dict:
55
- """
56
- Genera respuesta de TechMind
57
-
58
- Args:
59
- pregunta: Pregunta del usuario
60
- max_tokens: Longitud máxima de respuesta
61
- temperature: Creatividad (0.1=conservador, 1.0=creativo)
62
- top_p: Diversidad de vocabulario
63
-
64
- Returns:
65
- dict con 'respuesta', 'tiempo' y 'tokens'
66
- """
67
-
68
- # Construir prompt
69
- prompt = f"{SYSTEM_PROMPT}Pregunta: {pregunta}\nRespuesta: "
70
-
71
- # Tokenizar
72
- inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
73
-
74
- # Medir tiempo
75
- start_time = time.time()
76
-
77
- # Generar
78
- with torch.no_grad():
79
- outputs = model.generate(
80
- **inputs,
81
- max_new_tokens=max_tokens,
82
- temperature=temperature,
83
- top_p=top_p,
84
- do_sample=True,
85
- pad_token_id=tokenizer.eos_token_id,
86
- eos_token_id=tokenizer.eos_token_id,
87
- repetition_penalty=1.15,
88
- no_repeat_ngram_size=3
89
- )
90
-
91
- elapsed_time = time.time() - start_time
92
-
93
- # Decodificar
94
- respuesta_completa = tokenizer.decode(outputs[0], skip_special_tokens=True)
95
-
96
- # Limpiar (quitar prompt)
97
- if "Respuesta:" in respuesta_completa:
98
- respuesta = respuesta_completa.split("Respuesta:", 1)[-1].strip()
99
- else:
100
- respuesta = respuesta_completa
101
-
102
- # Calcular tokens
103
- tokens_generados = len(outputs[0]) - len(inputs["input_ids"][0])
104
-
105
- return {
106
- "respuesta": respuesta,
107
- "tiempo": round(elapsed_time, 2),
108
- "tokens": tokens_generados
109
- }
110
-
111
- # =========================================================
112
- # MODO INTERACTIVO
113
- # =========================================================
114
- def modo_interactivo():
115
- """Chat interactivo con TechMind"""
116
-
117
- print("=" * 70)
118
- print("🧠 TECHMIND PRO - Modo Interactivo")
119
- print("=" * 70)
120
- print("Escribe 'salir' para terminar")
121
- print("Escribe 'ajustes' para cambiar parámetros")
122
- print()
123
-
124
- # Parámetros por defecto
125
- config = {
126
- "max_tokens": 400,
127
- "temperature": 0.6,
128
- "top_p": 0.9
129
- }
130
-
131
- while True:
132
- try:
133
- pregunta = input("👤 Tú: ").strip()
134
-
135
- if pregunta.lower() in ["salir", "exit", "quit"]:
136
- print("👋 ¡Hasta luego!")
137
- break
138
-
139
- if pregunta.lower() == "ajustes":
140
- print("\n⚙️ Ajustes actuales:")
141
- print(f" max_tokens: {config['max_tokens']}")
142
- print(f" temperature: {config['temperature']}")
143
- print(f" top_p: {config['top_p']}")
144
- print()
145
- continue
146
-
147
- if not pregunta:
148
- continue
149
-
150
- # Generar respuesta
151
- print("🤖 TechMind: ", end="", flush=True)
152
-
153
- resultado = ask_techmind(
154
- pregunta,
155
- max_tokens=config["max_tokens"],
156
- temperature=config["temperature"],
157
- top_p=config["top_p"]
158
- )
159
-
160
- print(resultado["respuesta"])
161
- print(f"\n⏱️ {resultado['tiempo']}s | 📊 {resultado['tokens']} tokens\n")
162
-
163
- except KeyboardInterrupt:
164
- print("\n👋 ¡Hasta luego!")
165
- break
166
-
167
- except Exception as e:
168
- print(f"\n❌ Error: {e}\n")
169
-
170
- # =========================================================
171
- # EJEMPLOS DE USO
172
- # =========================================================
173
- def ejemplos():
174
- """Muestra ejemplos de uso"""
175
-
176
- print("\n" + "=" * 70)
177
- print("📝 EJEMPLOS DE USO")
178
- print("=" * 70)
179
-
180
- preguntas_ejemplo = [
181
- "¿Cómo configuro OSPF área 0 en un router Cisco?",
182
- "Dame comandos para diagnosticar packet loss",
183
- "¿Qué es BGP y cuándo debo usarlo?"
184
- ]
185
-
186
- for i, pregunta in enumerate(preguntas_ejemplo, 1):
187
- print(f"\n{i}. Pregunta: {pregunta}")
188
- print("-" * 70)
189
-
190
- resultado = ask_techmind(pregunta, max_tokens=300)
191
-
192
- print(f"Respuesta: {resultado['respuesta']}")
193
- print(f"⏱️ {resultado['tiempo']}s | 📊 {resultado['tokens']} tokens")
194
- print()
195
-
196
- # =========================================================
197
- # FUNCIÓN PARA API (FastAPI/Flask)
198
- # =========================================================
199
- def generar_respuesta_api(pregunta: str) -> dict:
200
- """
201
- Función optimizada para usar en API web
202
-
203
- Returns:
204
- dict con respuesta y metadata
205
- """
206
-
207
- try:
208
- resultado = ask_techmind(
209
- pregunta,
210
- max_tokens=400,
211
- temperature=0.6
212
- )
213
-
214
- return {
215
- "success": True,
216
- "respuesta": resultado["respuesta"],
217
- "tiempo_generacion": resultado["tiempo"],
218
- "tokens_generados": resultado["tokens"]
219
- }
220
-
221
- except Exception as e:
222
- return {
223
- "success": False,
224
- "error": str(e)
225
- }
226
-
227
- # =========================================================
228
- # MAIN
229
- # =========================================================
230
- if __name__ == "__main__":
231
- import sys
232
-
233
- if len(sys.argv) > 1:
234
- # Modo comando: python inference_techmind.py "tu pregunta"
235
- pregunta = " ".join(sys.argv[1:])
236
- resultado = ask_techmind(pregunta)
237
- print(resultado["respuesta"])
238
-
239
- elif "--ejemplos" in sys.argv or "-e" in sys.argv:
240
- # Modo ejemplos
241
- ejemplos()
242
-
243
- else:
244
- # Modo interactivo por defecto
245
- modo_interactivo()