File size: 16,033 Bytes
5b90b0d
a306750
7f3dfcc
a306750
 
cbbd51f
a306750
167f6e6
295803f
a306750
 
cbbd51f
 
 
f4672c6
 
 
 
 
295803f
 
a306750
 
 
 
5b90b0d
 
a306750
 
820eb4b
 
 
 
 
 
 
 
 
 
 
 
a306750
 
 
 
 
 
 
 
 
 
c350bb5
 
 
 
 
 
 
 
 
 
 
aade08d
a306750
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f047bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cbbd51f
f4672c6
 
a306750
 
f4672c6
a306750
cbbd51f
 
 
 
 
 
 
 
 
f18e6b9
f4672c6
 
 
 
 
 
a306750
aade08d
cbbd51f
 
 
f4672c6
cbbd51f
 
f4672c6
 
295803f
f4672c6
 
 
 
 
 
 
295803f
 
 
 
 
 
 
 
f4672c6
295803f
f4672c6
 
 
295803f
f4672c6
 
 
 
 
 
 
295803f
f4672c6
 
cbbd51f
 
 
bf69cdf
f4672c6
 
 
 
 
 
cbbd51f
 
f4672c6
cbbd51f
 
 
 
f4672c6
 
 
a306750
cbbd51f
f56bb7e
cbbd51f
 
 
 
 
 
 
 
 
07968d5
cbbd51f
 
 
 
 
 
 
 
 
3294219
f4672c6
cbbd51f
295803f
08b4bf9
295803f
cbbd51f
08b4bf9
cbbd51f
08b4bf9
cbbd51f
 
 
 
 
 
e279e64
295803f
 
a306750
295803f
 
 
 
 
 
 
 
99af063
 
295803f
99af063
 
 
 
 
 
 
 
295803f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99af063
295803f
 
 
 
cbbd51f
f4672c6
 
 
295803f
f4672c6
 
 
 
 
 
 
 
 
 
 
 
295803f
99af063
 
 
 
 
 
f4672c6
 
99af063
f4672c6
 
99af063
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4672c6
 
cbbd51f
 
 
 
295803f
 
 
 
 
a306750
f4672c6
 
99af063
 
 
 
f4672c6
a306750
cbbd51f
 
 
 
a306750
 
 
99af063
f4672c6
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import cachetools
from pydantic import BaseModel
from llama_cpp import Llama
from concurrent.futures import ThreadPoolExecutor, as_completed
import asyncio
import os
from dotenv import load_dotenv
from fastapi import FastAPI
from fastapi.responses import StreamingResponse, JSONResponse
import uvicorn
from threading import Thread
import psutil
import gc
import torch
import numpy as np
from PIL import Image
import stable_diffusion_cpp as sdcpp
import base64
import io
import time
from typing import AsyncGenerator

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>',
        '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',
        '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": {},
    '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_type': {},
    'image_model': {}
}


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": "city96/FLUX.1-schnell-gguf",
        "filename": "flux1-schnell-Q2_K.gguf",
        "name": "flux1-schnell"
     },
    
]

class ModelManager:
    def __init__(self):
        self.models = {}
        self.image_model = None

    def load_model(self, model_config):
        if model_config['name'] not in self.models and model_config['name'] != "flux1-schnell":
           try:
               print(f"Loading model: {model_config['name']}")
               self.models[model_config['name']] = Llama.from_pretrained(
                  repo_id=model_config['repo_id'],
                  filename=model_config['filename'],
                  use_auth_token=HUGGINGFACE_TOKEN,
                  n_threads=20,
                  use_gpu=False
               )
               print(f"Model loaded: {model_config['name']}")
               # Load tokenizer after model load
               if model_config['name'] not in global_data['tokenizers']:
                    global_data['tokenizers'][model_config['name']] = self.models[model_config['name']].tokenizer()
                    print(f"tokenizer loaded for: {model_config['name']}")
                    # load the eos token
                    global_data['eos'][model_config['name']] = self.models[model_config['name']].token_eos()
                    print(f"eos loaded for: {model_config['name']}")
           except Exception as e:
               print(f"Error loading model {model_config['name']}: {e}")

    def load_image_model(self, model_config):
       try:
          print(f"Attempting to load image model with config: {model_config}")
          self.image_model = sdcpp.StableDiffusionCpp(
              repo_id=model_config['repo_id'],
              filename=model_config['filename'],
              use_auth_token=HUGGINGFACE_TOKEN,
              n_threads=20,
              use_gpu=False
          )
          print(f"Image model loaded successfully: {self.image_model}")
       except Exception as e:
         print(f"Error loading image model: {e}")

    def load_all_models(self):
        with ThreadPoolExecutor() as executor:
            for config in model_configs:
                if config['name'] == "flux1-schnell":
                   executor.submit(self.load_image_model, config)
                else:
                    executor.submit(self.load_model, config)
        return self.models, self.image_model


model_manager = ModelManager()
global_data['models'], global_data['image_model'] = model_manager.load_all_models()

class ChatRequest(BaseModel):
    message: str

class ImageRequest(BaseModel):
    prompt: str

def normalize_input(input_text):
    return input_text.strip()

def remove_duplicates(text):
    lines = text.split('\n')
    unique_lines = []
    seen_lines = set()
    for line in lines:
        if line not in seen_lines:
            unique_lines.append(line)
            seen_lines.add(line)
    return '\n'.join(unique_lines)

def cache_response(func):
    def wrapper(*args, **kwargs):
        cache_key = f"{args}-{kwargs}"
        if cache_key in cache:
            return cache[cache_key]
        response = func(*args, **kwargs)
        cache[cache_key] = response
        return response
    return wrapper


@cache_response
def generate_model_response(model, inputs, max_tokens=9999999):
    try:
        response = model(inputs, max_tokens=max_tokens)
        return remove_duplicates(response['choices'][0]['text'])
    except Exception as e:
        return ""

def remove_repetitive_responses(responses):
    unique_responses = {}
    for response in responses:
        if response['model'] not in unique_responses:
            unique_responses[response['model']] = response['response']
    return unique_responses


async def process_message(message: str):
    inputs = normalize_input(message)
    
    async def stream_response(inputs: str) -> AsyncGenerator[str, None]:
            max_token_limit = 150
            full_response = ""
            current_inputs = inputs
            eos_found = False
            
            start_time = time.time()
            
            executor = ThreadPoolExecutor()
            while current_inputs and not eos_found:
                futures = [
                    executor.submit(generate_model_response, model, current_inputs, max_tokens=max_token_limit)
                    for model in global_data['models'].values()
                ]
                responses = [
                    {'model': model_name, 'response': future.result()}
                    for model_name, future in zip(global_data['models'].keys(), as_completed(futures))
                ]
                unique_responses = remove_repetitive_responses(responses)
                formatted_response = next(iter(unique_responses.values()))
                
                print(f"Generated chunk: {formatted_response}")
                
                
                #tokenize the response
                tokenizer = next(iter(global_data['tokenizers'].values()))
                tokens = tokenizer.encode(formatted_response)
                
                
                token_count = len(tokens)
                chunk_size = 30 # Set token chunk size
                for i in range(0, token_count, chunk_size):
                  chunk_tokens = tokens[i : i + chunk_size]
                  decoded_chunk = tokenizer.decode(chunk_tokens)
                  yield decoded_chunk
                
                # Check for EOS token in decoded chunk
                
                eos_token = next(iter(global_data['eos'].values()))
                if eos_token in tokens:
                   eos_found = True
                   print(f"End of sequence token found")
                   break
                
                full_response += formatted_response
                current_inputs = formatted_response if len(formatted_response.split()) > 0 else ""
            
            end_time = time.time()
            executor.shutdown(wait=True) # waits for all threads to finish
            print(f"Total time taken to process response {end_time-start_time}")
            
    return StreamingResponse(stream_response(inputs), media_type="text/plain")


async def generate_image(prompt: str):
    if global_data['image_model']:
        try:
            print("Generating image with prompt:", prompt)
            image_bytes = global_data['image_model'].generate(
                prompt=prompt,
                negative_prompt="ugly, deformed, disfigured",
                steps=25,
                cfg_scale=7.0,
                width=512,
                height=512,
                seed=-1,
                return_type='bytes'
             )
             
            image = Image.open(io.BytesIO(image_bytes))
            print("Image generated successfully.")
            
            buffered = io.BytesIO()
            image.save(buffered, format="PNG")
            image_base64 = base64.b64encode(buffered.getvalue()).decode()

            return JSONResponse(content={"image": image_base64})
        except Exception as e:
           print(f"Error generating image: {e}")
           return JSONResponse(content={"error": str(e)})
    else:
         print("No image model loaded.")
         return JSONResponse(content={"error": "No image model loaded"})

def release_resources():
    try:
        torch.cuda.empty_cache()
        gc.collect()
    except Exception as e:
        print(f"Failed to release resources: {e}")

def resource_manager():
    MAX_RAM_PERCENT = 10
    MAX_CPU_PERCENT = 10
    MAX_GPU_PERCENT = 10
    MAX_RAM_MB = 1024 # 1GB

    while True:
        try:
            virtual_mem = psutil.virtual_memory()
            current_ram_percent = virtual_mem.percent
            current_ram_mb = virtual_mem.used / (1024 * 1024)  # Convert to MB

            if current_ram_percent > MAX_RAM_PERCENT or current_ram_mb > MAX_RAM_MB:
                release_resources()

            current_cpu_percent = psutil.cpu_percent()
            if current_cpu_percent > MAX_CPU_PERCENT:
               print("CPU usage too high, attempting to reduce nice")
               p = psutil.Process(os.getpid())
               p.nice(1)

            if torch.cuda.is_available():
                gpu = torch.cuda.current_device()
                gpu_mem = torch.cuda.memory_percent(gpu)

                if gpu_mem > MAX_GPU_PERCENT:
                    release_resources()

            time.sleep(10) # Check every 10 seconds
        except Exception as e:
            print(f"Error in resource manager: {e}")
    

app = FastAPI()

@app.post("/generate")
async def generate(request: ChatRequest):
   try:
      return await process_message(request.message)
   except Exception as e:
      return JSONResponse(content={"error": str(e)})
        

@app.post("/generate_image")
async def generate_image_endpoint(request: ImageRequest):
   try:
       return await generate_image(request.prompt)
   except Exception as e:
       return JSONResponse(content={"error": str(e)})

def run_uvicorn():
    try:
        uvicorn.run(app, host="0.0.0.0", port=7860)
    except Exception as e:
        print(f"Error al ejecutar uvicorn: {e}")

if __name__ == "__main__":
    Thread(target=run_uvicorn).start()
    Thread(target=resource_manager, daemon=True).start()  # Run resource manager in background
    asyncio.get_event_loop().run_forever()