Uhhy commited on
Commit
8c32c92
1 Parent(s): c906d48

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -0
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, Request
2
+ import uvicorn
3
+ import requests
4
+ import os
5
+ import io
6
+ import time
7
+ import asyncio
8
+ from typing import List, Dict, Any
9
+ from tqdm import tqdm
10
+ from llama_cpp import Llama
11
+ import aiofiles
12
+
13
+ app = FastAPI()
14
+
15
+ # Configuración de los modelos
16
+ model_configs = [
17
+ {"repo_id": "Ffftdtd5dtft/gpt2-xl-Q2_K-GGUF", "filename": "gpt2-xl-q2_k.gguf", "name": "GPT-2 XL"},
18
+ {"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"},
19
+ {"repo_id": "Ffftdtd5dtft/gemma-2-9b-it-Q2_K-GGUF", "filename": "gemma-2-9b-it-q2_k.gguf", "name": "Gemma 2-9B IT"},
20
+ {"repo_id": "Ffftdtd5dtft/gemma-2-27b-Q2_K-GGUF", "filename": "gemma-2-27b-q2_k.gguf", "name": "Gemma 2-27B"},
21
+ {"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"},
22
+ {"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"},
23
+ {"repo_id": "Ffftdtd5dtft/Qwen2-7B-Instruct-Q2_K-GGUF", "filename": "qwen2-7b-instruct-q2_k.gguf", "name": "Qwen2 7B Instruct"},
24
+ {"repo_id": "Ffftdtd5dtft/starcoder2-3b-Q2_K-GGUF", "filename": "starcoder2-3b-q2_k.gguf", "name": "Starcoder2 3B"},
25
+ {"repo_id": "Ffftdtd5dtft/Qwen2-1.5B-Instruct-Q2_K-GGUF", "filename": "qwen2-1.5b-instruct-q2_k.gguf", "name": "Qwen2 1.5B Instruct"},
26
+ {"repo_id": "Ffftdtd5dtft/starcoder2-15b-Q2_K-GGUF", "filename": "starcoder2-15b-q2_k.gguf", "name": "Starcoder2 15B"},
27
+ {"repo_id": "Ffftdtd5dtft/gemma-2-2b-it-Q2_K-GGUF", "filename": "gemma-2-2b-it-q2_k.gguf", "name": "Gemma 2-2B IT"},
28
+ {"repo_id": "Ffftdtd5dtft/sarvam-2b-v0.5-Q2_K-GGUF", "filename": "sarvam-2b-v0.5-q2_k.gguf", "name": "Sarvam 2B v0.5"},
29
+ {"repo_id": "Ffftdtd5dtft/WizardLM-13B-Uncensored-Q2_K-GGUF", "filename": "wizardlm-13b-uncensored-q2_k.gguf", "name": "WizardLM 13B Uncensored"},
30
+ {"repo_id": "Ffftdtd5dtft/Qwen2-Math-72B-Instruct-Q2_K-GGUF", "filename": "qwen2-math-72b-instruct-q2_k.gguf", "name": "Qwen2 Math 72B Instruct"},
31
+ {"repo_id": "Ffftdtd5dtft/WizardLM-7B-Uncensored-Q2_K-GGUF", "filename": "wizardlm-7b-uncensored-q2_k.gguf", "name": "WizardLM 7B Uncensored"},
32
+ {"repo_id": "Ffftdtd5dtft/Qwen2-Math-7B-Instruct-Q2_K-GGUF", "filename": "qwen2-math-7b-instruct-q2_k.gguf", "name": "Qwen2 Math 7B Instruct"}
33
+ ]
34
+
35
+ class ModelManager:
36
+ def __init__(self):
37
+ self.models = {}
38
+ self.model_parts = {}
39
+ self.load_lock = asyncio.Lock()
40
+ self.index_lock = asyncio.Lock()
41
+ self.part_size = 1024 * 1024 # Tamaño de cada parte en bytes (1 MB)
42
+
43
+ async def download_model_to_memory(self, model_config):
44
+ url = f"https://huggingface.co/{model_config['repo_id']}/resolve/main/{model_config['filename']}"
45
+ print(f"Descargando modelo desde {url}")
46
+ try:
47
+ start_time = time.time()
48
+ response = requests.get(url)
49
+ response.raise_for_status()
50
+ end_time = time.time()
51
+ download_duration = end_time - start_time
52
+ print(f"Descarga completa para {model_config['name']} en {download_duration:.2f} segundos")
53
+ return io.BytesIO(response.content)
54
+ except requests.RequestException as e:
55
+ raise HTTPException(status_code=500, detail=f"Error al descargar el modelo: {e}")
56
+
57
+ async def save_model_to_temp_file(self, model_config):
58
+ model_file = await self.download_model_to_memory(model_config)
59
+ temp_filename = f"/tmp/{model_config['filename']}"
60
+ print(f"Guardando el modelo en {temp_filename}")
61
+ async with aiofiles.open(temp_filename, 'wb') as f:
62
+ await f.write(model_file.getvalue())
63
+ print(f"Modelo guardado en {temp_filename}")
64
+ return temp_filename
65
+
66
+ async def load_model(self, model_config):
67
+ async with self.load_lock:
68
+ try:
69
+ temp_filename = await self.save_model_to_temp_file(model_config)
70
+ start_time = time.time()
71
+ print(f"Cargando modelo desde {temp_filename}")
72
+
73
+ # Cambiar la forma en que se carga el modelo según la biblioteca que utilices
74
+ llama = Llama.from_file(temp_filename)
75
+
76
+ end_time = time.time()
77
+ load_duration = end_time - start_time
78
+ if load_duration > 0.5:
79
+ print(f"Modelo {model_config['name']} tardó {load_duration:.2f} segundos en cargar, dividiendo automáticamente")
80
+ await self.handle_large_model(temp_filename, model_config)
81
+ else:
82
+ print(f"Modelo {model_config['name']} cargado correctamente en {load_duration:.2f} segundos")
83
+
84
+ tokenizer = llama.tokenizer
85
+ model_data = {
86
+ 'model': llama,
87
+ 'tokenizer': tokenizer,
88
+ 'pad_token': tokenizer.pad_token,
89
+ 'pad_token_id': tokenizer.pad_token_id,
90
+ 'eos_token': tokenizer.eos_token,
91
+ 'eos_token_id': tokenizer.eos_token_id,
92
+ 'bos_token': tokenizer.bos_token,
93
+ 'bos_token_id': tokenizer.bos_token_id,
94
+ 'unk_token': tokenizer.unk_token,
95
+ 'unk_token_id': tokenizer.unk_token_id
96
+ }
97
+
98
+ self.models[model_config['name']] = model_data
99
+ except Exception as e:
100
+ print(f"Error al cargar el modelo: {e}")
101
+
102
+ async def handle_large_model(self, model_filename, model_config):
103
+ total_size = os.path.getsize(model_filename)
104
+ num_parts = (total_size + self.part_size - 1) // self.part_size
105
+
106
+ print(f"Modelo {model_config['name']} dividido en {num_parts} partes")
107
+ with open(model_filename, 'rb') as file:
108
+ for i in tqdm(range(num_parts), desc=f"Indexando {model_config['name']}"):
109
+ start = i * self.part_size
110
+ end = min(start + self.part_size, total_size)
111
+ file.seek(start)
112
+ model_part = io.BytesIO(file.read(end - start))
113
+ await self.index_model_part(model_part, i)
114
+
115
+ async def index_model_part(self, model_part, part_index):
116
+ async with self.index_lock:
117
+ part_name = f"part_{part_index}"
118
+ print(f"Indexando parte {part_index}")
119
+ temp_filename = f"/tmp/{part_name}.gguf"
120
+ async with aiofiles.open(temp_filename, 'wb') as f:
121
+ await f.write(model_part.getvalue())
122
+ print(f"Parte {part_index} indexada y guardada")
123
+
124
+ async def generate_response(self, user_input):
125
+ results = []
126
+ for model_name, model_data in self.models.items():
127
+ try:
128
+ tokenizer = model_data['tokenizer']
129
+ input_ids = tokenizer(user_input, return_tensors="pt").input_ids
130
+ outputs = model_data['model'].generate(input_ids)
131
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
132
+
133
+ # Dividir el texto generado en partes
134
+ parts = []
135
+ while len(generated_text) > 1000:
136
+ part = generated_text[:1000]
137
+ parts.append(part)
138
+ generated_text = generated_text[1000:]
139
+ parts.append(generated_text)
140
+
141
+ results.append({
142
+ 'model_name': model_name,
143
+ 'generated_text_parts': parts
144
+ })
145
+ except Exception as e:
146
+ print(f"Error al generar respuesta con el modelo {model_name}: {e}")
147
+ results.append({'model_name': model_name, 'error': str(e)})
148
+
149
+ return results
150
+
151
+ @app.post("/generate/")
152
+ async def generate(request: Request):
153
+ data = await request.json()
154
+ user_input = data.get('input', '')
155
+ if not user_input:
156
+ raise HTTPException(status_code=400, detail="Se requiere una entrada de usuario.")
157
+
158
+ try:
159
+ model_manager = ModelManager()
160
+ tasks = [model_manager.load_model(config) for config in model_configs]
161
+ await asyncio.gather(*tasks)
162
+ responses = await model_manager.generate_response(user_input)
163
+ return {"responses": responses}
164
+ except Exception as e:
165
+ raise HTTPException(status_code=500, detail=str(e))
166
+
167
+ def start_uvicorn():
168
+ uvicorn.run(app, host="0.0.0.0", port=8000)
169
+
170
+ if __name__ == "__main__":
171
+ asyncio.run(start_uvicorn())