File size: 8,578 Bytes
6053333
 
 
5b90b0d
a306750
7f3dfcc
a306750
 
 
 
 
6053333
a306750
0a97d8a
a306750
 
 
5b90b0d
f56bb7e
 
4f047bc
 
 
 
a306750
 
 
 
5b90b0d
 
a306750
 
820eb4b
 
 
 
 
 
 
 
 
 
 
 
 
a306750
 
 
 
 
 
 
 
 
 
 
820eb4b
 
 
 
 
 
 
 
 
 
 
ef9123a
a306750
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f047bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a306750
 
 
6053333
 
 
4f047bc
a306750
 
 
4f047bc
 
 
 
f56bb7e
0a97d8a
08b4bf9
4f047bc
 
08b4bf9
 
 
e279e64
 
 
a306750
 
eb492f1
 
f56bb7e
 
a306750
 
 
 
0a97d8a
af41c5b
0a97d8a
 
af41c5b
 
 
a306750
 
6053333
a306750
 
 
 
 
 
5b90b0d
a306750
 
 
 
 
 
 
 
5b90b0d
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import os
import gc
import psutil
import cachetools
from pydantic import BaseModel
from llama_cpp import Llama
from concurrent.futures import ThreadPoolExecutor, as_completed
import re
import httpx
import asyncio
import gradio as gr
import torch
from dotenv import load_dotenv
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import uvicorn
from threading import Thread
import gptcache
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer
import nltk
from nltk.corpus import stopwords

nltk.download('stopwords')

load_dotenv()
HUGGINGFACE_TOKEN = os.getenv("HUGGINGFACE_TOKEN")

cache = cachetools.TTLCache(maxsize=100, ttl=60)

global_data = {
    'models': {},
    'tokensxx': {
        'eos': '<|end_of-text|>',
        'pad': '<pad>',
        'padding': '<pad>',
        'unk': '<unk>',
        'bos': '<|begin_of_text|>',
        'sep': '<|sep|>',
        'cls': '<|cls|>',
        'mask': '<mask>',
        'eot': '<|eot_id|>',
        'eom': '<|eom_id|>',
        'lf': '<|0x0A|>'
    },
    'tokens': {
        'eos': 'eos_token',
        'pad': 'pad_token',
        'padding': 'padding_token',
        'unk': 'unk_token',
        'bos': 'bos_token',
        'sep': 'sep_token',
        'cls': 'cls_token',
        'mask': 'mask_token'
    },
    'model_metadata': {},
    'eos': {},
    'pad': {},
    'padding': {},
    'unk': {},
    'bos': {},
    'sep': {},
    'cls': {},
    'mask': {},
    'eot': {},
    'eom': {},
    'lf': {},
    'max_tokens': {},
    'tokenizers': {},
    'model_params': {},
    'model_size': {},
    'model_ftype': {},
    'n_ctx_train': {},
    'n_embd': {},
    'n_layer': {},
    'n_head': {},
    'n_head_kv': {},
    'n_rot': {},
    'n_swa': {},
    'n_embd_head_k': {},
    'n_embd_head_v': {},
    'n_gqa': {},
    'n_embd_k_gqa': {},
    'n_embd_v_gqa': {},
    'f_norm_eps': {},
    'f_norm_rms_eps': {},
    'f_clamp_kqv': {},
    'f_max_alibi_bias': {},
    'f_logit_scale': {},
    'n_ff': {},
    'n_expert': {},
    'n_expert_used': {},
    'causal_attn': {},
    'pooling_type': {},
    'rope_type': {},
    'rope_scaling': {},
    'freq_base_train': {},
    'freq_scale_train': {},
    'n_ctx_orig_yarn': {},
    'rope_finetuned': {},
    'ssm_d_conv': {},
    'ssm_d_inner': {},
    'ssm_d_state': {},
    'ssm_dt_rank': {},
    'ssm_dt_b_c_rms': {},
    'vocab_type': {},
    'model_type': {},
    "general.architecture": {},
    "general.type": {},
    "general.name": {},
    "general.finetune": {},
    "general.basename": {},
    "general.size_label": {},
    "general.license": {},
    "general.license.link": {},
    "general.tags": {},
    "general.languages": {},
    "general.organization": {},
    "general.base_model.count": {},
    'general.file_type': {},
    "phi3.context_length": {},
    "phi3.rope.scaling.original_context_length": {},
    "phi3.embedding_length": {},
    "phi3.feed_forward_length": {},
    "phi3.block_count": {},
    "phi3.attention.head_count": {},
    "phi3.attention.head_count_kv": {},
    "phi3.attention.layer_norm_rms_epsilon": {},
    "phi3.rope.dimension_count": {},
    "phi3.rope.freq_base": {},
    "phi3.attention.sliding_window": {},
    "phi3.rope.scaling.attn_factor": {},
    "llama.block_count": {},
    "llama.context_length": {},
    "llama.embedding_length": {},
    "llama.feed_forward_length": {},
    "llama.attention.head_count": {},
    "llama.attention.head_count_kv": {},
    "llama.rope.freq_base": {},
    "llama.attention.layer_norm_rms_epsilon": {},
    "llama.attention.key_length": {},
    "llama.attention.value_length": {},
    "llama.vocab_size": {},
    "llama.rope.dimension_count": {},
    "deepseek2.block_count": {},
    "deepseek2.context_length": {},
    "deepseek2.embedding_length": {},
    "deepseek2.feed_forward_length": {},
    "deepseek2.attention.head_count": {},
    "deepseek2.attention.head_count_kv": {},
    "deepseek2.rope.freq_base": {},
    "deepseek2.attention.layer_norm_rms_epsilon": {},
    "deepseek2.expert_used_count": {},
    "deepseek2.leading_dense_block_count": {},
    "deepseek2.vocab_size": {},
    "deepseek2.attention.kv_lora_rank": {},
    "deepseek2.attention.key_length": {},
    "deepseek2.attention.value_length": {},
    "deepseek2.expert_feed_forward_length": {},
    "deepseek2.expert_count": {},
    "deepseek2.expert_shared_count": {},
    "deepseek2.expert_weights_scale": {},
    "deepseek2.rope.dimension_count": {},
    "deepseek2.rope.scaling.type": {},
    "deepseek2.rope.scaling.factor": {},
    "deepseek2.rope.scaling.yarn_log_multiplier": {},
    "qwen2.block_count": {},
    "qwen2.context_length": {},
    "qwen2.embedding_length": {},
    "qwen2.feed_forward_length": {},
    "qwen2.attention.head_count": {},
    "qwen2.attention.head_count_kv": {},
    "qwen2.rope.freq_base": {},
    "qwen2.attention.layer_norm_rms_epsilon": {},
    "general.version": {},
    "general.datasets": {},
    "tokenizer.ggml.model": {},
    "tokenizer.ggml.pre": {},
    "tokenizer.ggml.tokens": {},
    "tokenizer.ggml.token_type": {},
    "tokenizer.ggml.merges": {},
    "tokenizer.ggml.bos_token_id": {},
    "tokenizer.ggml.eos_token_id": {},
    "tokenizer.ggml.unknown_token_id": {},
    "tokenizer.ggml.padding_token_id": {},
    "tokenizer.ggml.add_bos_token": {},
    "tokenizer.ggml.add_eos_token": {},
    "tokenizer.ggml.add_space_prefix": {},
    "tokenizer.chat_template": {},
    "quantize.imatrix.file": {},
    "quantize.imatrix.dataset": {},
    "quantize.imatrix.entries_count": {},
    "quantize.imatrix.chunks_count": {},
    "general.quantization_version": {},
    'n_lora_q': {},
    'n_lora_kv': {},
    'n_expert_shared': {},
    'n_ff_exp': {},
    "n_layer_dense_lead": {},
    "expert_weights_scale": {},
    "rope_yarn_log_mul": {},
    'model_type': {},
    'eval': {},
    'time': {},
    'token': {},
    'tokens': {},
    'pads': {},
    'model': {},
    'base': {},
    'model_base': {},
    'perhaps': {},
    'word': {},
    'words': {},
    'start': {},
    'stop': {},
    'run': {},
    'runs': {},
    'ms': {},
    'vocabulary': {},
    'timeout': {},
    'load': {},
    'load_time': {},
    'bas': {},
    'tok': {},
    'second': {},
    'seconds': {},
    'graph': {},
    'load_model': {},
    'end': {},
    'llama_perf_context_print': {},
    'llm_load_print_meta': {}
}

model_configs = [
    {"repo_id": "Hjgugugjhuhjggg/testing_semifinal-Q2_K-GGUF", "filename": "testing_semifinal-q2_k.gguf", "name": "testing"},
    {"repo_id": "bartowski/Llama-3.2-3B-Instruct-uncensored-GGUF", "filename": "Llama-3.2-3B-Instruct-uncensored-Q2_K.gguf", "name": "Llama-3.2-3B-Instruct"},
    {"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"},
    {"repo_id": "Hhhbvvkgh/Heidi-Llama-v4-Q2_K-GGUF", "filename": "heidi-llama-v4-q2_k.gguf", "name": "Heidi-Llama-V4"}
]

def normalize_input(input_text):
    stop_words = set(stopwords.words('english'))
    words = input_text.split()
    filtered_words = [word for word in words if word.lower() not in stop_words]
    return " ".join(filtered_words)

async def generate_model_response(model, inputs):
    try:
        response = await model.generate(inputs)
        return response
    except Exception as e:
        return ""

def get_best_response(responses):
    return max(responses, key=lambda x: x['score'])

async def process_message(message):
    inputs = normalize_input(message)
    tasks = [generate_model_response(model, inputs) for model in global_data['models'].values()]
    responses = await asyncio.gather(*tasks)
    best_response = get_best_response(responses)
    return best_response

app = FastAPI()

@app.post("/generate")
async def generate(request: Request):
    try:
        body = await request.json()
        response = await process_message(body['message'])
        return JSONResponse(content={"response": response})
    except Exception as e:
        return JSONResponse(content={"error": str(e)})

def run_uvicorn():
    uvicorn.run(app, host="0.0.0.0", port=7860)

iface = gr.Interface(
    fn=process_message,
    inputs=gr.Textbox(lines=2, placeholder="Enter your message here..."),
    outputs=gr.Markdown(),
    title="Multi-Model LLM API (CPU Optimized)",
    description=""
)

def run_gradio():
    iface.launch(server_port=7862, prevent_thread_lock=True)

if __name__ == "__main__":
    Thread(target=run_uvicorn).start()
    Thread(target=run_gradio).start()
    asyncio.get_event_loop().run_forever()