X commited on
Commit
85e5355
·
verified ·
1 Parent(s): a9462f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +6 -11
app.py CHANGED
@@ -47,7 +47,6 @@ MAX_LEN = 25
47
  def tokenize(text):
48
  return [word_to_idx.get(w, UNK) for w in text.lower().split()]
49
 
50
- # Жесткая фильтрация спецтокенов при выводе
51
  def detokenize(tokens):
52
  words = []
53
  for t in tokens:
@@ -201,16 +200,16 @@ class AndreyAI:
201
  'num_layers': 2, 'dim_feedforward': 256,
202
  'word_to_idx': word_to_idx,
203
  'idx_to_word': {str(k): v for k, v in idx_to_word.items()},
204
- 'memory': self.memory, 'version': '11.0-No-ZeroGPU-Train',
205
  'created': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
206
  }
207
  torch.save(state, self.bin_file)
208
  print(f"✅ Сохранено .bin: {os.path.getsize(self.bin_file)/1024:.1f} КБ")
209
 
210
- # ВАЖНО: Убран декоратор @spaces.GPU. Обучение идет мгновенно на CPU/GPU без очереди.
211
  def train(self, epochs=50):
212
- print(f"🚀 Обучение ({epochs} эпох) на доступном устройстве...")
213
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
214
  self.model.to(device)
215
  self.model.train()
216
 
@@ -246,7 +245,6 @@ class AndreyAI:
246
  print(f"Эпоха {epoch}/{epochs} | Loss: {total_loss/n_batches:.4f}")
247
 
248
  self.memory['epochs_trained'] += epochs
249
- self.model.cpu()
250
  self.save_weights()
251
  return f"✅ Обучение завершено! Эпох: {self.memory['epochs_trained']}"
252
 
@@ -257,7 +255,7 @@ class AndreyAI:
257
  if q in q_clean or q_clean in q: return a
258
  return "Я пока учусь, но стараюсь понимать тебя."
259
 
260
- # Генерация оставлена под @spaces.GPU для стабильности в среде Hugging Face
261
  @spaces.GPU(duration=10)
262
  def generate_tokens(self, question, history=None, temperature=0.3, max_length=15):
263
  device = torch.device('cuda')
@@ -265,8 +263,6 @@ class AndreyAI:
265
  self.model.eval()
266
 
267
  q = question.lower().strip()
268
-
269
- # Подаем на вход ТОЛЬКО текст пользователя, как при обучении
270
  ctx_tokens = tokenize(q)
271
  if not ctx_tokens:
272
  self.model.cpu()
@@ -291,7 +287,6 @@ class AndreyAI:
291
  _, next_token = torch.max(probs, dim=-1)
292
  next_token = next_token.item()
293
 
294
- # Защита от спецтокенов и зацикливания
295
  if next_token in [PAD, UNK, START] or next_token == last_token:
296
  break
297
 
@@ -334,7 +329,7 @@ def start_training():
334
  return andrey.train(epochs=50)
335
 
336
  with gr.Blocks(title="Андрей AI") as demo:
337
- gr.Markdown("# 🤖 Андрей AI (Оптимизированный)\n### Обучение без ZeroGPU, мгновенный стриминг")
338
 
339
  chatbot = gr.Chatbot(height=400, label="Диалог")
340
  msg = gr.Textbox(label="Сообщение", placeholder="Напишите что-нибудь...")
 
47
  def tokenize(text):
48
  return [word_to_idx.get(w, UNK) for w in text.lower().split()]
49
 
 
50
  def detokenize(tokens):
51
  words = []
52
  for t in tokens:
 
200
  'num_layers': 2, 'dim_feedforward': 256,
201
  'word_to_idx': word_to_idx,
202
  'idx_to_word': {str(k): v for k, v in idx_to_word.items()},
203
+ 'memory': self.memory, 'version': '11.1-CPU-Train-Fixed',
204
  'created': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
205
  }
206
  torch.save(state, self.bin_file)
207
  print(f"✅ Сохранено .bin: {os.path.getsize(self.bin_file)/1024:.1f} КБ")
208
 
209
+ # ИСПРАВЛЕНИЕ: Явно указываем 'cpu', чтобы обойти блокировку ZeroGPU
210
  def train(self, epochs=50):
211
+ print(f"🚀 Обучение ({epochs} эпох) на CPU (быстро и без лимитов ZeroGPU)...")
212
+ device = torch.device('cpu') # <-- КЛЮЧЕВОЕ ИЗМЕНЕНИЕ
213
  self.model.to(device)
214
  self.model.train()
215
 
 
245
  print(f"Эпоха {epoch}/{epochs} | Loss: {total_loss/n_batches:.4f}")
246
 
247
  self.memory['epochs_trained'] += epochs
 
248
  self.save_weights()
249
  return f"✅ Обучение завершено! Эпох: {self.memory['epochs_trained']}"
250
 
 
255
  if q in q_clean or q_clean in q: return a
256
  return "Я пока учусь, но стараюсь понимать тебя."
257
 
258
+ # Генерация ОСТАЕТСЯ под @spaces.GPU, так как это единственный способ использовать GPU в ZeroGPU
259
  @spaces.GPU(duration=10)
260
  def generate_tokens(self, question, history=None, temperature=0.3, max_length=15):
261
  device = torch.device('cuda')
 
263
  self.model.eval()
264
 
265
  q = question.lower().strip()
 
 
266
  ctx_tokens = tokenize(q)
267
  if not ctx_tokens:
268
  self.model.cpu()
 
287
  _, next_token = torch.max(probs, dim=-1)
288
  next_token = next_token.item()
289
 
 
290
  if next_token in [PAD, UNK, START] or next_token == last_token:
291
  break
292
 
 
329
  return andrey.train(epochs=50)
330
 
331
  with gr.Blocks(title="Андрей AI") as demo:
332
+ gr.Markdown("# 🤖 Андрей AI (Оптимизированный)\n### Обучение на CPU (0 секунд лимита), генерация на ZeroGPU")
333
 
334
  chatbot = gr.Chatbot(height=400, label="Диалог")
335
  msg = gr.Textbox(label="Сообщение", placeholder="Напишите что-нибудь...")