Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from pydantic import BaseModel
|
3 |
+
from langchain import LLMChain
|
4 |
+
from langchain.llms import Llama
|
5 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
6 |
+
from tqdm import tqdm
|
7 |
+
import uvicorn
|
8 |
+
from dotenv import load_dotenv
|
9 |
+
import io
|
10 |
+
import requests
|
11 |
+
import asyncio
|
12 |
+
import time
|
13 |
+
|
14 |
+
# Cargar variables de entorno
|
15 |
+
load_dotenv()
|
16 |
+
|
17 |
+
# Inicializar aplicación FastAPI
|
18 |
+
app = FastAPI()
|
19 |
+
|
20 |
+
# Configuración de los modelos
|
21 |
+
model_configs = [
|
22 |
+
{"repo_id": "Ffftdtd5dtft/gpt2-xl-Q2_K-GGUF", "filename": "gpt2-xl-q2_k.gguf", "name": "GPT-2 XL"},
|
23 |
+
{"repo_id": "Ffftdtd5dtft/Meta-Llama-3.1-8B-Instruct-Q2_K-GGUF", "filename": "meta-llama-3.1-8b-instruct-q2_k.gguf", "name": "Meta Llama 3.1-8B Instruct"},
|
24 |
+
{"repo_id": "Ffftdtd5dtft/gemma-2-9b-it-Q2_K-GGUF", "filename": "gemma-2-9b-it-q2_k.gguf", "name": "Gemma 2-9B IT"},
|
25 |
+
{"repo_id": "Ffftdtd5dtft/gemma-2-27b-Q2_K-GGUF", "filename": "gemma-2-27b-q2_k.gguf", "name": "Gemma 2-27B"},
|
26 |
+
{"repo_id": "Ffftdtd5dtft/Phi-3-mini-128k-instruct-Q2_K-GGUF", "filename": "phi-3-mini-128k-instruct-q2_k.gguf", "name": "Phi-3 Mini 128K Instruct"},
|
27 |
+
{"repo_id": "Ffftdtd5dtft/Meta-Llama-3.1-8B-Q2_K-GGUF", "filename": "meta-llama-3.1-8b-q2_k.gguf", "name": "Meta Llama 3.1-8B"},
|
28 |
+
{"repo_id": "Ffftdtd5dtft/Qwen2-7B-Instruct-Q2_K-GGUF", "filename": "qwen2-7b-instruct-q2_k.gguf", "name": "Qwen2 7B Instruct"},
|
29 |
+
{"repo_id": "Ffftdtd5dtft/starcoder2-3b-Q2_K-GGUF", "filename": "starcoder2-3b-q2_k.gguf", "name": "Starcoder2 3B"},
|
30 |
+
{"repo_id": "Ffftdtd5dtft/Qwen2-1.5B-Instruct-Q2_K-GGUF", "filename": "qwen2-1.5b-instruct-q2_k.gguf", "name": "Qwen2 1.5B Instruct"},
|
31 |
+
{"repo_id": "Ffftdtd5dtft/starcoder2-15b-Q2_K-GGUF", "filename": "starcoder2-15b-q2_k.gguf", "name": "Starcoder2 15B"},
|
32 |
+
{"repo_id": "Ffftdtd5dtft/gemma-2-2b-it-Q2_K-GGUF", "filename": "gemma-2-2b-it-q2_k.gguf", "name": "Gemma 2-2B IT"},
|
33 |
+
{"repo_id": "Ffftdtd5dtft/sarvam-2b-v0.5-Q2_K-GGUF", "filename": "sarvam-2b-v0.5-q2_k.gguf", "name": "Sarvam 2B v0.5"},
|
34 |
+
{"repo_id": "Ffftdtd5dtft/WizardLM-13B-Uncensored-Q2_K-GGUF", "filename": "wizardlm-13b-uncensored-q2_k.gguf", "name": "WizardLM 13B Uncensored"},
|
35 |
+
{"repo_id": "Ffftdtd5dtft/Qwen2-Math-72B-Instruct-Q2_K-GGUF", "filename": "qwen2-math-72b-instruct-q2_k.gguf", "name": "Qwen2 Math 72B Instruct"},
|
36 |
+
{"repo_id": "Ffftdtd5dtft/WizardLM-7B-Uncensored-Q2_K-GGUF", "filename": "wizardlm-7b-uncensored-q2_k.gguf", "name": "WizardLM 7B Uncensored"},
|
37 |
+
{"repo_id": "Ffftdtd5dtft/Qwen2-Math-7B-Instruct-Q2_K-GGUF", "filename": "qwen2-math-7b-instruct-q2_k.gguf", "name": "Qwen2 Math 7B Instruct"}
|
38 |
+
]
|
39 |
+
|
40 |
+
# Clase para gestionar modelos
|
41 |
+
class ModelManager:
|
42 |
+
def __init__(self):
|
43 |
+
self.models = []
|
44 |
+
self.configs = {}
|
45 |
+
|
46 |
+
async def download_model_to_memory(self, model_config):
|
47 |
+
print(f"Descargando modelo: {model_config['name']}...")
|
48 |
+
url = f"https://huggingface.co/{model_config['repo_id']}/resolve/main/{model_config['filename']}"
|
49 |
+
response = requests.get(url)
|
50 |
+
if response.status_code == 200:
|
51 |
+
model_file = io.BytesIO(response.content)
|
52 |
+
return model_file
|
53 |
+
else:
|
54 |
+
raise Exception(f"Error al descargar el modelo: {response.status_code}")
|
55 |
+
|
56 |
+
async def load_model(self, model_config):
|
57 |
+
try:
|
58 |
+
start_time = time.time()
|
59 |
+
model_file = await self.download_model_to_memory(model_config)
|
60 |
+
print(f"Cargando modelo: {model_config['name']}...")
|
61 |
+
|
62 |
+
# Simulación de división de carga si el tiempo excede 1 segundo
|
63 |
+
async def load_part(part):
|
64 |
+
# Esta función simula la carga de una parte del modelo
|
65 |
+
await asyncio.sleep(0.1) # Simula un pequeño retraso en la carga
|
66 |
+
|
67 |
+
# Se divide la carga en partes si excede 1 segundo
|
68 |
+
if time.time() - start_time > 1:
|
69 |
+
print(f"Modelo {model_config['name']} tardó más de 1 segundo en cargarse, dividiendo la carga...")
|
70 |
+
await asyncio.gather(*(load_part(part) for part in range(5))) # Simulación de división en 5 partes
|
71 |
+
else:
|
72 |
+
model = await asyncio.get_event_loop().run_in_executor(
|
73 |
+
None,
|
74 |
+
lambda: Llama.from_pretrained(model_file)
|
75 |
+
)
|
76 |
+
|
77 |
+
model = await asyncio.get_event_loop().run_in_executor(
|
78 |
+
None,
|
79 |
+
lambda: Llama.from_pretrained(model_file)
|
80 |
+
)
|
81 |
+
tokenizer = model.tokenizer
|
82 |
+
|
83 |
+
# Almacenar tokens y tokenizer en la RAM
|
84 |
+
model_data = {
|
85 |
+
'model': model,
|
86 |
+
'tokenizer': tokenizer,
|
87 |
+
'pad_token': tokenizer.pad_token,
|
88 |
+
'pad_token_id': tokenizer.pad_token_id,
|
89 |
+
'eos_token': tokenizer.eos_token,
|
90 |
+
'eos_token_id': tokenizer.eos_token_id,
|
91 |
+
'bos_token': tokenizer.bos_token,
|
92 |
+
'bos_token_id': tokenizer.bos_token_id,
|
93 |
+
'unk_token': tokenizer.unk_token,
|
94 |
+
'unk_token_id': tokenizer.unk_token_id
|
95 |
+
}
|
96 |
+
|
97 |
+
self.models.append({"model_data": model_data, "name": model_config['name']})
|
98 |
+
except Exception as e:
|
99 |
+
print(f"Error al cargar el modelo: {e}")
|
100 |
+
|
101 |
+
async def load_all_models(self):
|
102 |
+
print("Iniciando carga de modelos...")
|
103 |
+
start_time = time.time()
|
104 |
+
tasks = [self.load_model(config) for config in model_configs]
|
105 |
+
await asyncio.gather(*tasks)
|
106 |
+
end_time = time.time()
|
107 |
+
print(f"Todos los modelos han sido cargados en {end_time - start_time:.2f} segundos.")
|
108 |
+
|
109 |
+
# Instanciar ModelManager y cargar modelos
|
110 |
+
model_manager = ModelManager()
|
111 |
+
|
112 |
+
@app.on_event("startup")
|
113 |
+
async def startup_event():
|
114 |
+
await model_manager.load_all_models()
|
115 |
+
|
116 |
+
# Modelo global para la solicitud de chat
|
117 |
+
class ChatRequest(BaseModel):
|
118 |
+
message: str
|
119 |
+
top_k: int = 50
|
120 |
+
top_p: float = 0.95
|
121 |
+
temperature: float = 0.7
|
122 |
+
|
123 |
+
# Límite de tokens para respuestas
|
124 |
+
TOKEN_LIMIT = 1000 # Define el límite de tokens permitido por respuesta
|
125 |
+
|
126 |
+
# Función para generar respuestas de chat
|
127 |
+
async def generate_chat_response(request, model_data):
|
128 |
+
try:
|
129 |
+
user_input = normalize_input(request.message)
|
130 |
+
llm = model_data['model_data']['model']
|
131 |
+
tokenizer = model_data['model_data']['tokenizer']
|
132 |
+
|
133 |
+
# Generar respuesta de manera rápida
|
134 |
+
response = await asyncio.get_event_loop().run_in_executor(
|
135 |
+
None,
|
136 |
+
lambda: llm(user_input, max_length=TOKEN_LIMIT, do_sample=True, top_k=request.top_k, top_p=request.top_p, temperature=request.temperature)
|
137 |
+
)
|
138 |
+
generated_text = response['generated_text']
|
139 |
+
# Dividir respuesta larga
|
140 |
+
split_response = split_long_response(generated_text)
|
141 |
+
return {"response": split_response, "literal": user_input, "model_name": model_data['name']}
|
142 |
+
except Exception as e:
|
143 |
+
print(f"Error al generar la respuesta: {e}")
|
144 |
+
return {"response": "Error al generar la respuesta", "literal": user_input, "model_name": model_data['name']}
|
145 |
+
|
146 |
+
def split_long_response(response):
|
147 |
+
""" Divide la respuesta en partes más pequeñas si excede el límite de tokens. """
|
148 |
+
parts = []
|
149 |
+
while len(response) > TOKEN_LIMIT:
|
150 |
+
part = response[:TOKEN_LIMIT]
|
151 |
+
response = response[TOKEN_LIMIT:]
|
152 |
+
parts.append(part.strip())
|
153 |
+
if response:
|
154 |
+
parts.append(response.strip())
|
155 |
+
return '\n'.join(parts)
|
156 |
+
|
157 |
+
def remove_duplicates(text):
|
158 |
+
""" Elimina duplicados en el texto. """
|
159 |
+
lines = text.splitlines()
|
160 |
+
unique_lines = list(dict.fromkeys(lines))
|
161 |
+
return '\n'.join(unique_lines)
|
162 |
+
|
163 |
+
def remove_repetitive_responses(responses):
|
164 |
+
unique_responses = []
|
165 |
+
seen_responses = set()
|
166 |
+
for response in responses:
|
167 |
+
normalized_response = remove_duplicates(response['response'])
|
168 |
+
if normalized_response not in seen_responses:
|
169 |
+
seen_responses.add(normalized_response)
|
170 |
+
response['response'] = normalized_response
|
171 |
+
unique_responses.append(response)
|
172 |
+
return unique_responses
|
173 |
+
|
174 |
+
@app.post("/chat")
|
175 |
+
async def chat(request: ChatRequest):
|
176 |
+
results = []
|
177 |
+
for model_data in model_manager.models:
|
178 |
+
response = await generate_chat_response(request, model_data)
|
179 |
+
results.append(response)
|
180 |
+
unique_results = remove_repetitive_responses(results)
|
181 |
+
return {"results": unique_results}
|
182 |
+
|
183 |
+
# Ejecutar la aplicación FastAPI
|
184 |
+
if __name__ == "__main__":
|
185 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|