Hjgugugjhuhjggg commited on
Commit
c1a1630
1 Parent(s): 9bc4091

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -336
app.py CHANGED
@@ -15,342 +15,6 @@ from threading import Thread
15
  from time import sleep
16
  from fastapi.staticfiles import StaticFiles
17
  import gradio as gr
18
-
19
- load_dotenv()
20
-
21
- HUGGINGFACE_TOKEN = os.getenv("HUGGINGFACE_TOKEN")
22
-
23
- global_data = {
24
- 'models': {},
25
- }
26
-
27
- model_configs = [
28
- {"repo_id": "Ffftdtd5dtft/gpt2-xl-Q2_K-GGUF", "filename": "gpt2-xl-q2_k.gguf", "name": "GPT-2 XL"},
29
- {"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"},
30
- {"repo_id": "Ffftdtd5dtft/gemma-2-9b-it-Q2_K-GGUF", "filename": "gemma-2-9b-it-q2_k.gguf", "name": "Gemma 2-9B IT"},
31
- {"repo_id": "Ffftdtd5dtft/gemma-2-27b-Q2_K-GGUF", "filename": "gemma-2-27b-q2_k.gguf", "name": "Gemma 2-27B"},
32
- {"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"},
33
- {"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"},
34
- {"repo_id": "Ffftdtd5dtft/Qwen2-7B-Instruct-Q2_K-GGUF", "filename": "qwen2-7b-instruct-q2_k.gguf", "name": "Qwen2 7B Instruct"},
35
- {"repo_id": "Ffftdtd5dtft/starcoder2-3b-Q2_K-GGUF", "filename": "starcoder2-3b-q2_k.gguf", "name": "Starcoder2 3B"},
36
- {"repo_id": "Ffftdtd5dtft/Qwen2-1.5B-Instruct-Q2_K-GGUF", "filename": "qwen2-1.5b-instruct-q2_k.gguf", "name": "Qwen2 1.5B Instruct"},
37
- {"repo_id": "Ffftdtd5dtft/Meta-Llama-3.1-70B-Q2_K-GGUF", "filename": "meta-llama-3.1-70b-q2_k.gguf", "name": "Meta Llama 3.1-70B"},
38
- {"repo_id": "Ffftdtd5dtft/Mistral-Nemo-Instruct-2407-Q2_K-GGUF", "filename": "mistral-nemo-instruct-2407-q2_k.gguf", "name": "Mistral Nemo Instruct 2407"},
39
- {"repo_id": "Ffftdtd5dtft/Hermes-3-Llama-3.1-8B-IQ1_S-GGUF", "filename": "hermes-3-llama-3.1-8b-iq1_s-imat.gguf", "name": "Hermes 3 Llama 3.1-8B"},
40
- {"repo_id": "Ffftdtd5dtft/Phi-3.5-mini-instruct-Q2_K-GGUF", "filename": "phi-3.5-mini-instruct-q2_k.gguf", "name": "Phi 3.5 Mini Instruct"},
41
- {"repo_id": "Ffftdtd5dtft/Meta-Llama-3.1-70B-Instruct-Q2_K-GGUF", "filename": "meta-llama-3.1-70b-instruct-q2_k.gguf", "name": "Meta Llama 3.1-70B Instruct"},
42
- {"repo_id": "Ffftdtd5dtft/codegemma-2b-IQ1_S-GGUF", "filename": "codegemma-2b-iq1_s-imat.gguf", "name": "Codegemma 2B"},
43
- {"repo_id": "Ffftdtd5dtft/Phi-3-mini-128k-instruct-IQ2_XXS-GGUF", "filename": "phi-3-mini-128k-instruct-iq2_xxs-imat.gguf", "name": "Phi 3 Mini 128K Instruct XXS"},
44
- {"repo_id": "Ffftdtd5dtft/TinyLlama-1.1B-Chat-v1.0-IQ1_S-GGUF", "filename": "tinyllama-1.1b-chat-v1.0-iq1_s-imat.gguf", "name": "TinyLlama 1.1B Chat"},
45
- {"repo_id": "Ffftdtd5dtft/Mistral-NeMo-Minitron-8B-Base-IQ1_S-GGUF", "filename": "mistral-nemo-minitron-8b-base-iq1_s-imat.gguf", "name": "Mistral NeMo Minitron 8B Base"},
46
- {"repo_id": "Ffftdtd5dtft/Mistral-Nemo-Instruct-2407-Q2_K-GGUF", "filename": "mistral-nemo-instruct-2407-q2_k.gguf", "name": "Mistral Nemo Instruct 2407"}
47
- ]
48
-
49
- class ModelManager:
50
- def __init__(self):
51
- self.models = {}
52
-
53
- def load_model(self, model_config):
54
- if model_config['name'] not in self.models:
55
- try:
56
- print(f"Loading model {model_config['name']}...")
57
- self.models[model_config['name']] = Llama.from_pretrained(
58
- repo_id=model_config['repo_id'],
59
- filename=model_config['filename'],
60
- use_auth_token=HUGGINGFACE_TOKEN
61
- )
62
- print(f"Model {model_config['name']} loaded successfully.")
63
- except Exception as e:
64
- print(f"Error loading model {model_config['name']}: {e}")
65
-
66
- def load_all_models(self):
67
- with ThreadPoolExecutor() as executor:
68
- for config in model_configs:
69
- executor.submit(self.load_model, config)
70
- return self.models
71
-
72
- model_manager = ModelManager()
73
- global_data['models'] = model_manager.load_all_models()
74
-
75
- class ChatRequest(BaseModel):
76
- message: str
77
-
78
- def normalize_input(input_text):
79
- return input_text.strip()
80
-
81
- def remove_duplicates(text):
82
- text = re.sub(r'(Hello there, how are you\? \[/INST\]){2,}', 'Hello there, how are you? [/INST]', text)
83
- text = re.sub(r'(How are you\? \[/INST\]){2,}', 'How are you? [/INST]', text)
84
- text = text.replace('[/INST]', '')
85
- lines = text.split('\n')
86
- unique_lines = []
87
- seen_lines = set()
88
- for line in lines:
89
- if line not in seen_lines:
90
- unique_lines.append(line)
91
- seen_lines.add(line)
92
- return '\n'.join(unique_lines)
93
-
94
- PROXY_URL = "https://uhhy-fsfsfs.hf.space/valid"
95
-
96
- def get_random_proxy():
97
- try:
98
- response = requests.get(PROXY_URL)
99
- proxies = response.text.splitlines()
100
- return random.choice(proxies)
101
- except Exception as e:
102
- print(f"Error fetching proxy: {e}")
103
- return None
104
-
105
- fake = Faker()
106
-
107
- def generate_fake_ip():
108
- return fake.ipv4()
109
-
110
- def get_random_user_agent():
111
- user_agents = [
112
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
113
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
114
- "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
115
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
116
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7; rv:89.0) Gecko/20100101 Firefox/89.0",
117
- "Mozilla/5.0 (X11; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0",
118
- "Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Mobile/15E148 Safari/604.1",
119
- "Mozilla/5.0 (iPad; CPU OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Mobile/15E148 Safari/604.1",
120
- "Mozilla/5.0 (Android 11; Mobile; rv:89.0) Gecko/89.0 Firefox/89.0"
121
- ]
122
- return random.choice(user_agents)
123
-
124
- @spaces.GPU(
125
- queue=False,
126
- allow_gpu_memory=True,
127
- timeout=0,
128
- duration=0,
129
- gpu_type='Tesla V100',
130
- gpu_count=2,
131
- gpu_memory_limit='32GB',
132
- cpu_limit=4,
133
- memory_limit='64GB',
134
- retry=True,
135
- retry_delay=30,
136
- priority='high',
137
- disk_limit='100GB',
138
- scratch_space='/mnt/scratch',
139
- network_bandwidth_limit='200Mbps',
140
- internet_access=True,
141
- precision='float16',
142
- batch_size=128,
143
- num_threads=16,
144
- logging_level='DEBUG',
145
- log_to_file=True,
146
- alert_on_failure=True,
147
- data_encryption=True,
148
- env_variables={'CUDA_VISIBLE_DEVICES': '0'},
149
- environment_type='conda',
150
- enable_checkpointing=True,
151
- resource_limits={'gpu': 'Tesla V100', 'cpu': 8, 'memory': '128GB'},
152
- hyperparameter_tuning=True,
153
- prefetch_data=True,
154
- persistent_storage=True,
155
- auto_scaling=True,
156
- security_level='high',
157
- task_priority='urgent',
158
- retries_on_timeout=True,
159
- file_system='nfs',
160
- custom_metrics={'throughput': '300GB/s', 'latency': '10ms'},
161
- gpu_utilization_logging=True,
162
- job_isolation='container',
163
- failure_strategy='retry',
164
- gpu_memory_overcommit=True,
165
- cpu_overcommit=True,
166
- memory_overcommit=True,
167
- enable_optimizations=True,
168
- multi_gpu_strategy='data_parallel',
169
- model_parallelism=True,
170
- quantization='dynamic',
171
- pruning='structured',
172
- tensor_parallelism=True,
173
- mixed_precision_training=True,
174
- layerwise_lr_decay=True,
175
- warmup_steps=500,
176
- learning_rate_scheduler='cosine_annealing',
177
- dropout_rate=0.3,
178
- weight_decay=0.01,
179
- gradient_accumulation_steps=8,
180
- mixed_precision_loss_scale=128,
181
- tensorboard_logging=True,
182
- hyperparameter_search_space={'learning_rate': [1e-5, 1e-3], 'batch_size': [64, 256]},
183
- early_stopping=True,
184
- early_stopping_patience=10,
185
- input_data_pipeline='tf.data',
186
- batch_normalization=True,
187
- activation_function='relu',
188
- optimizer='adam',
189
- gradient_clipping=1.0,
190
- checkpoint_freq=10,
191
- experiment_name='deep_model_training',
192
- experiment_tags=['nlp', 'deep_learning'],
193
- adaptive_lr=True,
194
- learning_rate_max=0.01,
195
- learning_rate_min=1e-6,
196
- max_steps=100000,
197
- tolerance=0.01,
198
- logging_frequency=10,
199
- profile_gpu=True,
200
- profile_cpu=True,
201
- debug_mode=True,
202
- save_best_model=True,
203
- evaluation_metric='accuracy',
204
- job_preemption='enabled',
205
- preemptible_resources=True,
206
- grace_period=60,
207
- resource_scheduling='fifo',
208
- hyperparameter_optimization_algorithm='bayesian',
209
- distributed_training=True,
210
- multi_node_training=True,
211
- max_retries=5,
212
- log_level='INFO',
213
- secure_socket_layer=True,
214
- data_sharding=True,
215
- distributed_optimizer='horovod',
216
- mixed_precision_support=True,
217
- fault_tolerance=True,
218
- external_gpu_resources=True,
219
- disk_cache=True,
220
- backup_enabled=True,
221
- backup_frequency='daily',
222
- task_grouping='dynamic',
223
- instance_type='high_memory',
224
- instance_count=3,
225
- task_runtime='hours',
226
- adaptive_memory_allocation=True,
227
- model_versioning=True,
228
- multi_model_support=True,
229
- batch_optimization=True,
230
- memory_prefetch=True,
231
- data_prefetch_threads=16,
232
- network_optimization=True,
233
- model_parallelism_strategy='pipeline',
234
- verbose_logging=True,
235
- lock_on_failure=True,
236
- data_compression=True,
237
- inference_mode='batch',
238
- distributed_cache_enabled=True,
239
- dynamic_batching=True,
240
- model_deployment=True,
241
- latency_optimization=True,
242
- multi_region_deployment=True,
243
- multi_user_support=True,
244
- job_scheduling='auto',
245
- max_job_count=100,
246
- suspend_on_idle=True,
247
- hyperparameter_search_algorithm='random',
248
- job_priority_scaling=True,
249
- quantum_computing_support=True,
250
- dynamic_resource_scaling=True,
251
- runtime_optimization=True,
252
- checkpoint_interval='30min',
253
- max_gpu_temperature=80,
254
- scale_on_gpu_utilization=True,
255
- worker_threads=8
256
- )
257
- def generate_model_response(model, inputs):
258
- print(f"Generating response for model: {model}")
259
- response = model(inputs)
260
- print(f"Response from {model}: {response}")
261
- return remove_duplicates(response['choices'][0]['text'])
262
-
263
- def remove_repetitive_responses(responses):
264
- unique_responses = {}
265
- for response in responses:
266
- if response not in unique_responses:
267
- unique_responses[response] = response
268
- return unique_responses
269
-
270
- async def process_message(message):
271
- inputs = normalize_input(message)
272
- with ThreadPoolExecutor() as executor:
273
- futures = [
274
- executor.submit(generate_model_response, model, inputs)
275
- for model in global_data['models'].values()
276
- ]
277
- responses = []
278
- for future in as_completed(futures):
279
- try:
280
- response = future.result()
281
- responses.append(response)
282
- except Exception as e:
283
- print(f"Error with model: {e}")
284
- responses.append("Error generating response. Please try again later.")
285
-
286
- unique_responses = remove_repetitive_responses(responses)
287
- formatted_response = ""
288
- for model, response in unique_responses.items():
289
- formatted_response += f"**{model}:**\n{response}\n\n"
290
-
291
- curl_command = f"""
292
- curl -X POST -H "Content-Type: application/json" \\
293
- -d '{{"message": "{message}"}}' \\
294
- http://localhost:7860/generate
295
- """
296
- return formatted_response, curl_command
297
-
298
- app = FastAPI()
299
-
300
- app.add_middleware(
301
- CORSMiddleware,
302
- allow_origins=["*"],
303
- allow_credentials=True,
304
- allow_methods=["*"],
305
- allow_headers=["*"],
306
- )
307
-
308
- app.mount("/", StaticFiles(directory="public", html=True), name="static")
309
-
310
- @app.post("/generate")
311
- async def generate_response(request: Request):
312
- data = await request.json()
313
- message = data.get("message")
314
- if not message:
315
- return JSONResponse(status_code=400, content={"error": "Message is required."})
316
-
317
- response, _ = await process_message(message)
318
- return JSONResponse(content={"response": response})
319
-
320
- iface = gr.Interface(
321
- fn=process_message,
322
- inputs=gr.Textbox(lines=2, placeholder="Enter your message here..."),
323
- outputs=[gr.Markdown(), gr.Textbox(label="cURL command")],
324
- title="Multi-Model LLM API",
325
- description="Enter a message and get responses from multiple LLMs.",
326
- )
327
-
328
- def anonymize_ip():
329
- while True:
330
- sleep(0)
331
- os.environ['HTTP_X_FORWARDED_FOR'] = generate_fake_ip()
332
- os.environ['REMOTE_ADDR'] = generate_fake_ip()
333
-
334
- Thread(target=anonymize_ip).start()
335
-
336
- if __name__ == "__main__":
337
- iface.launch(share=True) from pydantic import BaseModel
338
- from llama_cpp import Llama
339
- from concurrent.futures import ThreadPoolExecutor, as_completed
340
- import re
341
- import os
342
- from dotenv import load_dotenv
343
- import spaces
344
- import requests
345
- import random
346
- from faker import Faker
347
- from fastapi import FastAPI, Request
348
- from fastapi.responses import JSONResponse
349
- from fastapi.middleware.cors import CORSMiddleware
350
- from threading import Thread
351
- from time import sleep
352
- from fastapi.staticfiles import StaticFiles
353
- import gradio as gr
354
  from typing import Dict, Any, Tuple
355
  from urllib.parse import urlparse
356
 
 
15
  from time import sleep
16
  from fastapi.staticfiles import StaticFiles
17
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  from typing import Dict, Any, Tuple
19
  from urllib.parse import urlparse
20