Gems234 commited on
Commit
13dd02d
·
verified ·
1 Parent(s): a6acd24

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -103
app.py CHANGED
@@ -29,31 +29,27 @@ if not os.path.exists(MODEL_PATH):
29
  print(f"❌ Erreur téléchargement: {e}")
30
 
31
  # -------------------------
32
- # CONFIGURATION LLAMA.CPP OPTIMISÉE POUR CPU
33
  # -------------------------
34
  os.environ["LLAMA_CPP_LOG_LEVEL"] = "OFF"
35
  warnings.filterwarnings("ignore")
36
 
37
- print("⚡ Chargement du modèle avec llama.cpp (CPU optimisé)...")
38
 
39
  # Détection automatique du nombre de threads
40
  import multiprocessing
41
  cpu_count = multiprocessing.cpu_count()
42
- n_threads = max(2, cpu_count - 1) # Utiliser tous les cores sauf un
43
 
44
  llm = Llama(
45
  model_path=MODEL_PATH,
46
- n_ctx=2048, # Contexte réduit pour meilleure performance
47
- n_gpu_layers=0, # Désactivé pour CPU uniquement
48
- n_threads=n_threads, # Optimisé pour votre CPU
49
- n_batch=512, # Batch adapté pour CPU
50
- n_threads_batch=n_threads, # Même nombre de threads pour le batch
51
- use_mlock=False, # Désactivé pour meilleures performances
52
- vocab_only=False,
53
  verbose=False
54
  )
55
 
56
- print(f"✅ Modèle chargé! Threads: {n_threads} | CPU: {cpu_count} cores")
57
 
58
  # -------------------------
59
  # ÉTAT & SYNCHRONISATION
@@ -61,6 +57,7 @@ print(f"✅ Modèle chargé! Threads: {n_threads} | CPU: {cpu_count} cores")
61
  lock = threading.Lock()
62
  conversations = {"Conversation 1": []}
63
  stop_generation = threading.Event()
 
64
 
65
  # -------------------------
66
  # FONCTIONS UTILITAIRES OPTIMISÉES
@@ -72,32 +69,28 @@ def get_conv_names():
72
  with lock:
73
  return list(conversations.keys())
74
 
75
- # Cache pour éviter la reconstruction complète du prompt
76
- prompt_cache = {}
77
  def build_conversation_prompt(history, new_message):
78
- """Format de prompt optimisé avec cache"""
79
- cache_key = str(len(history)) + new_message[:50]
80
-
81
- if cache_key in prompt_cache:
82
- return prompt_cache[cache_key]
83
 
84
  prompt = ""
85
 
86
- # System prompt seulement au début
87
- if not any(any(conv) for conv in conversations.values()):
88
- prompt += """Tu es Alisia, une assistante IA utile et compétente. Réponds de manière précise et concise.
 
 
89
 
90
  """
 
91
 
92
- # Historique de conversation (limité aux derniers messages)
93
- recent_history = history[-4:] # Limiter à 4 derniers échanges pour CPU
94
- for user_msg, assistant_msg in recent_history:
95
  prompt += f"### Instruction:\n{user_msg}\n\n### Response:\n{assistant_msg}\n\n"
96
 
97
- # Nouveau message
98
  prompt += f"### Instruction:\n{new_message}\n\n### Response:\n"
99
 
100
- prompt_cache[cache_key] = prompt
101
  return prompt
102
 
103
  def send_message_stream(user_message, displayed_history, current_chat_name):
@@ -121,24 +114,16 @@ def send_message_stream(user_message, displayed_history, current_chat_name):
121
  formatted_prompt = build_conversation_prompt(local_hist[:-1], str(user_message))
122
  partial = ""
123
 
124
- # PARAMÈTRES OPTIMISÉS POUR CPU
125
- last_update = time.time()
126
- token_count = 0
127
- min_tokens = 3 # Regroupement modéré pour CPU
128
- max_delay = 0.3 # 300ms entre updates pour CPU
129
- buffer = ""
130
-
131
  try:
 
132
  stream = llm.create_completion(
133
  prompt=formatted_prompt,
134
  stream=True,
135
- max_tokens=384, # Réponse plus courte pour CPU
136
  temperature=0.7,
137
- top_p=0.9,
138
- repeat_penalty=1.1,
139
- stop=["### Instruction:", "### Response:", "\n\n", "<|endoftext|>"],
140
- min_p=0.05, # Acceleration CPU
141
- typical_p=0.95 # Acceleration CPU
142
  )
143
 
144
  for chunk in stream:
@@ -148,35 +133,11 @@ def send_message_stream(user_message, displayed_history, current_chat_name):
148
  if "choices" in chunk and chunk["choices"]:
149
  token = chunk["choices"][0].get("text", "")
150
  if token:
151
- buffer += token
152
- token_count += 1
153
-
154
- # STRATÉGIE OPTIMISÉE POUR CPU
155
- current_time = time.time()
156
- time_since_update = current_time - last_update
157
-
158
- should_update = (
159
- token_count >= min_tokens or
160
- time_since_update > max_delay or
161
- token in [".", "!", "?", "\n", " "]
162
- )
163
-
164
- if should_update and buffer.strip():
165
- partial += buffer
166
- cleaned = clean_output(partial)
167
- local_hist[-1] = (str(user_message), cleaned)
168
- yield local_hist, ""
169
- last_update = current_time
170
- token_count = 0
171
- buffer = ""
172
-
173
- # Dernier flush du buffer
174
- if buffer:
175
- partial += buffer
176
- if partial:
177
- cleaned = clean_output(partial)
178
- local_hist[-1] = (str(user_message), cleaned)
179
- yield local_hist, ""
180
 
181
  except Exception as e:
182
  err_text = f"[Erreur: {e}]"
@@ -185,8 +146,7 @@ def send_message_stream(user_message, displayed_history, current_chat_name):
185
 
186
  finally:
187
  end_time = time.time()
188
- generation_time = end_time - start_time
189
- print(f"⏱️ Temps de génération: {generation_time:.2f}s - {len(partial)} caractères")
190
  with lock:
191
  conversations[current_chat_name] = local_hist.copy()
192
  yield local_hist, ""
@@ -215,12 +175,14 @@ def request_stop():
215
  return "🛑 Arrêt demandé..."
216
 
217
  def clear_chat():
 
218
  with lock:
219
  conversations["Conversation 1"] = []
 
220
  return [], "Conversation 1"
221
 
222
  # -------------------------
223
- # INTERFACE GRADIO OPTIMISÉE POUR CPU
224
  # -------------------------
225
  css = """
226
  :root {
@@ -401,26 +363,17 @@ css = """
401
  background: #1e293b;
402
  border-radius: 8px;
403
  }
404
-
405
- .cpu-warning {
406
- color: #fbbf24;
407
- background: #431407;
408
- padding: 8px;
409
- border-radius: 8px;
410
- margin-top: 10px;
411
- font-size: 12px;
412
- }
413
  """
414
 
415
- with gr.Blocks(css=css, title="Alisia Chat - Optimisé CPU", theme=gr.themes.Soft()) as demo:
416
  history_visible = gr.State(True)
417
  current_chat = gr.State("Conversation 1")
418
 
419
  with gr.Row(elem_id="topbar"):
420
  menu_btn = gr.Button("☰", elem_classes="hamburger")
421
- gr.Markdown("### 💬 Alisia <span class='alisia-badge'>CPU Mode</span>", elem_id="title")
422
  gr.HTML("<div style='flex:1'></div>")
423
- gr.Markdown(f"<small style='color:#94a3b8'>CPU: {cpu_count} coresThreads: {n_threads}</small>")
424
 
425
  with gr.Row():
426
  with gr.Column(scale=1, visible=True, elem_id="leftcol") as left_column:
@@ -442,21 +395,12 @@ with gr.Blocks(css=css, title="Alisia Chat - Optimisé CPU", theme=gr.themes.Sof
442
  elem_classes="clear-btn"
443
  )
444
 
445
- # Informations de performance CPU
446
  gr.Markdown("""
447
  <div class="perf-info">
448
- <strong> Mode CPU Optimisé</strong><br>
449
- Threads: {n_threads}/{cpu_count}<br>
450
- Contexte: 2048 tokens<br>
451
- Latence: ~300ms<br>
452
- • Réponses: 384 tokens max
453
- </div>
454
- """.format(n_threads=n_threads, cpu_count=cpu_count))
455
-
456
- gr.Markdown("""
457
- <div class="cpu-warning">
458
- ⚠️ Mode CPU - Les performances peuvent varier<br>
459
- selon la puissance de votre processeur
460
  </div>
461
  """)
462
 
@@ -556,13 +500,9 @@ with gr.Blocks(css=css, title="Alisia Chat - Optimisé CPU", theme=gr.themes.Sof
556
  # LANCEMENT
557
  # -------------------------
558
  if __name__ == "__main__":
559
- print("🚀 Lancement de l'interface optimisée CPU...")
560
- print(f"💻 Configuration CPU:")
561
- print(f" - Cores disponibles: {cpu_count}")
562
- print(f" - Threads utilisés: {n_threads}")
563
- print(f" - Contexte: 2048 tokens")
564
- print(f" - Réponses limitées: 384 tokens")
565
- print("⏱️ Patience - Le CPU peut être plus lent que le GPU")
566
 
567
  demo.launch(
568
  share=True,
 
29
  print(f"❌ Erreur téléchargement: {e}")
30
 
31
  # -------------------------
32
+ # CONFIGURATION LLAMA.CPP OPTIMISÉE
33
  # -------------------------
34
  os.environ["LLAMA_CPP_LOG_LEVEL"] = "OFF"
35
  warnings.filterwarnings("ignore")
36
 
37
+ print("⚡ Chargement du modèle avec llama.cpp...")
38
 
39
  # Détection automatique du nombre de threads
40
  import multiprocessing
41
  cpu_count = multiprocessing.cpu_count()
42
+ n_threads = max(2, cpu_count - 1)
43
 
44
  llm = Llama(
45
  model_path=MODEL_PATH,
46
+ n_ctx=2048,
47
+ n_gpu_layers=0, # CPU uniquement
48
+ n_threads=n_threads,
 
 
 
 
49
  verbose=False
50
  )
51
 
52
+ print(f"✅ Modèle chargé! Threads: {n_threads}")
53
 
54
  # -------------------------
55
  # ÉTAT & SYNCHRONISATION
 
57
  lock = threading.Lock()
58
  conversations = {"Conversation 1": []}
59
  stop_generation = threading.Event()
60
+ system_prompt_used = False # Pour suivre si le system prompt a été utilisé
61
 
62
  # -------------------------
63
  # FONCTIONS UTILITAIRES OPTIMISÉES
 
69
  with lock:
70
  return list(conversations.keys())
71
 
 
 
72
  def build_conversation_prompt(history, new_message):
73
+ """Format de prompt Alpaca avec system prompt UNIQUEMENT au début"""
74
+ global system_prompt_used
 
 
 
75
 
76
  prompt = ""
77
 
78
+ # System prompt UNIQUEMENT si jamais utilisé auparavant
79
+ if not system_prompt_used:
80
+ prompt += """Your name is Alisia, you are created by the Alisia research team.
81
+ Below is an instruction that describes a task, paired with an input that provides further context.
82
+ Write a response that appropriately completes the request.
83
 
84
  """
85
+ system_prompt_used = True
86
 
87
+ # Ajouter tout l'historique de conversation
88
+ for user_msg, assistant_msg in history:
 
89
  prompt += f"### Instruction:\n{user_msg}\n\n### Response:\n{assistant_msg}\n\n"
90
 
91
+ # Ajouter le nouveau message
92
  prompt += f"### Instruction:\n{new_message}\n\n### Response:\n"
93
 
 
94
  return prompt
95
 
96
  def send_message_stream(user_message, displayed_history, current_chat_name):
 
114
  formatted_prompt = build_conversation_prompt(local_hist[:-1], str(user_message))
115
  partial = ""
116
 
 
 
 
 
 
 
 
117
  try:
118
+ # Utilisation directe du streaming sans buffering complexe
119
  stream = llm.create_completion(
120
  prompt=formatted_prompt,
121
  stream=True,
122
+ max_tokens=1024,
123
  temperature=0.7,
124
+ top_p=0.8,
125
+ repeat_penalty=1.05,
126
+ stop=["### Instruction:", "### Response:", "<|endoftext|>", "\n\n\n"]
 
 
127
  )
128
 
129
  for chunk in stream:
 
133
  if "choices" in chunk and chunk["choices"]:
134
  token = chunk["choices"][0].get("text", "")
135
  if token:
136
+ partial += token
137
+ # Mise à jour immédiate pour une meilleure réactivité
138
+ cleaned = clean_output(partial)
139
+ local_hist[-1] = (str(user_message), cleaned)
140
+ yield local_hist, ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
  except Exception as e:
143
  err_text = f"[Erreur: {e}]"
 
146
 
147
  finally:
148
  end_time = time.time()
149
+ print(f"⏱️ Génération: {end_time - start_time:.2f}s - {len(partial)} chars")
 
150
  with lock:
151
  conversations[current_chat_name] = local_hist.copy()
152
  yield local_hist, ""
 
175
  return "🛑 Arrêt demandé..."
176
 
177
  def clear_chat():
178
+ global system_prompt_used
179
  with lock:
180
  conversations["Conversation 1"] = []
181
+ system_prompt_used = False # Réinitialiser pour le prochain chat
182
  return [], "Conversation 1"
183
 
184
  # -------------------------
185
+ # INTERFACE GRADIO OPTIMISÉE
186
  # -------------------------
187
  css = """
188
  :root {
 
363
  background: #1e293b;
364
  border-radius: 8px;
365
  }
 
 
 
 
 
 
 
 
 
366
  """
367
 
368
+ with gr.Blocks(css=css, title="Alisia Chat - Ultra Rapide", theme=gr.themes.Soft()) as demo:
369
  history_visible = gr.State(True)
370
  current_chat = gr.State("Conversation 1")
371
 
372
  with gr.Row(elem_id="topbar"):
373
  menu_btn = gr.Button("☰", elem_classes="hamburger")
374
+ gr.Markdown("### 💬 Alisia <span class='alisia-badge'>AI Assistant</span>", elem_id="title")
375
  gr.HTML("<div style='flex:1'></div>")
376
+ gr.Markdown(f"<small style='color:#94a3b8'>CPU: {n_threads} threadsMode Rapide</small>")
377
 
378
  with gr.Row():
379
  with gr.Column(scale=1, visible=True, elem_id="leftcol") as left_column:
 
395
  elem_classes="clear-btn"
396
  )
397
 
 
398
  gr.Markdown("""
399
  <div class="perf-info">
400
+ <strong>🚀 Mode Alpaca Optimisé</strong><br>
401
+ System prompt unique<br>
402
+ Streaming direct<br>
403
+ Format Alpaca pur
 
 
 
 
 
 
 
 
404
  </div>
405
  """)
406
 
 
500
  # LANCEMENT
501
  # -------------------------
502
  if __name__ == "__main__":
503
+ print("🚀 Lancement de l'interface optimisée...")
504
+ print("📋 Format Alpaca avec system prompt unique")
505
+ print(f" Threads CPU: {n_threads}")
 
 
 
 
506
 
507
  demo.launch(
508
  share=True,