VaxiusK commited on
Commit
2a2f3b3
·
verified ·
1 Parent(s): bfca39c
Files changed (1) hide show
  1. app.py +247 -0
app.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =====================================================
2
+ # TINYLLAMA 1.1B + 12 ДАТАСЕТОВ | 75 000 ШАГОВ
3
+ # С ЛОГАМИ В TELEGRAM И АВТО-ОТПРАВКОЙ ССЫЛКИ
4
+ # =====================================================
5
+
6
+ # 1. УСТАНОВКА
7
+ !pip install -q unsloth datasets transformers trl accelerate requests
8
+
9
+ import json
10
+ import torch
11
+ import random
12
+ import requests
13
+ import time
14
+ import os
15
+ import shutil
16
+ import datetime
17
+ from datasets import Dataset, concatenate_datasets, load_dataset
18
+ from unsloth import FastLanguageModel
19
+ from trl import SFTTrainer, SFTConfig
20
+ from google.colab import drive
21
+
22
+ # =====================================================
23
+ # НАСТРОЙКИ TELEGRAM
24
+ # =====================================================
25
+ BOT_TOKEN = "8552885780:AAGDEjeEHhW03VYodRRmU_0fHPrx8b9GqH4"
26
+ CHAT_ID = "8552885780" # Твой Telegram ID (можно оставить как есть, бот сам определит)
27
+
28
+ def send_tg_message(text):
29
+ """Отправляет сообщение в Telegram"""
30
+ try:
31
+ url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
32
+ payload = {"chat_id": CHAT_ID, "text": text, "parse_mode": "HTML"}
33
+ response = requests.post(url, json=payload, timeout=10)
34
+ return response.ok
35
+ except Exception as e:
36
+ print(f"Ошибка отправки сообщения: {e}")
37
+ return False
38
+
39
+ def send_tg_file(file_path, caption=""):
40
+ """Отправляет файл в Telegram (если он меньше 50 МБ)"""
41
+ try:
42
+ file_size = os.path.getsize(file_path) / (1024 * 1024)
43
+ if file_size > 45: # Оставляем запас 5 МБ
44
+ send_tg_message(f"⚠️ Файл {os.path.basename(file_path)} слишком большой ({file_size:.1f} МБ). Отправляю только ссылку.")
45
+ return False
46
+ url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendDocument"
47
+ with open(file_path, "rb") as f:
48
+ files = {"document": f}
49
+ data = {"chat_id": CHAT_ID, "caption": caption}
50
+ response = requests.post(url, files=files, data=data, timeout=60)
51
+ return response.ok
52
+ except Exception as e:
53
+ print(f"Ошибка отправки файла: {e}")
54
+ return False
55
+
56
+ send_tg_message("🚀 <b>Запущено обучение TinyLlama 1.1B</b>\n📚 12 датасетов\n🎯 75 000 шагов\n⏱️ Ожидаемое время: 2-3 часа")
57
+ print("✅ Telegram бот подключён")
58
+
59
+ # 2. МОНТИРУЕМ DRIVE
60
+ drive.mount('/content/drive')
61
+ send_tg_message("✅ Google Drive смонтирован")
62
+ print("✅ Google Drive смонтирован")
63
+
64
+ # 3. ЗАГРУЗКА МОДЕЛИ
65
+ send_tg_message("🧠 Загружаю модель TinyLlama 1.1B...")
66
+ print("\n🧠 Загружаем TinyLlama 1.1B...")
67
+ model, tokenizer = FastLanguageModel.from_pretrained(
68
+ "unsloth/tinyllama-bnb-4bit",
69
+ max_seq_length=2048,
70
+ load_in_4bit=True,
71
+ )
72
+
73
+ model = FastLanguageModel.get_peft_model(
74
+ model,
75
+ r=32,
76
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
77
+ lora_alpha=32,
78
+ lora_dropout=0,
79
+ )
80
+ send_tg_message("✅ Модель загружена")
81
+
82
+ # =====================================================
83
+ # 4. ЗАГРУЗКА 12 ДАТАСЕТОВ
84
+ # =====================================================
85
+ send_tg_message("📚 Начинаю загрузку 12 датасетов...")
86
+ print("\n📚 Загружаю 12 датасетов...")
87
+
88
+ def convert_to_standard(example):
89
+ instr = (example.get("instruction") or example.get("prompt") or
90
+ example.get("query") or example.get("question") or
91
+ example.get("conversation") or example.get("text") or "")
92
+ out = (example.get("output") or example.get("response") or
93
+ example.get("answer") or example.get("completion") or
94
+ example.get("chosen") or "")
95
+ if isinstance(instr, list):
96
+ instr = str(instr[0]) if instr else ""
97
+ if isinstance(out, list):
98
+ out = str(out[0]) if out else ""
99
+ if instr and out:
100
+ return {"instruction": str(instr)[:1000], "output": str(out)[:1000]}
101
+ return None
102
+
103
+ dataset_links = [
104
+ ("princeton-nlp/gemma2-ultrafeedback-armorm", "Ультрафидбек"),
105
+ ("sanjay920/gemma-function-calling", "Функции"),
106
+ ("Jackrong/qwen3-coder-480b-distill-mini", "Кодер"),
107
+ ("masint/qwen3-30b-a3b-instruct-deflate-general", "Инструкции"),
108
+ ("mizinovmv/ru_codefeedback_python_Qwen2.5-Coder-32B-Instruct-GPTQ-Int8_sample", "Русский код"),
109
+ ("YuminChoi/ThinkSafe-qwen-0.6B-ablation-prompt-risk", "Безопасность"),
110
+ ("Crownelius/UltraCHAT-4200x-Qwen3", "Чаты"),
111
+ ("Congliu/Chinese-DeepSeek-R1-Distill-data-110k", "Китайский R1"),
112
+ ("Kedreamix/psychology-10k-Deepseek-R1-zh", "Психология"),
113
+ ("Trelis/openassistant-deepseek-coder", "Код ассистент"),
114
+ ("TeichAI/DeepSeek-v4-Pro-Agent", "Агент"),
115
+ ("SuperbEmphasis/Claude-4.0-DeepSeek-R1-RP-SFWish", "Ролевые"),
116
+ ]
117
+
118
+ all_datasets = []
119
+ for link, name in dataset_links:
120
+ try:
121
+ send_tg_message(f"📥 Загружаю {name}...")
122
+ print(f" Загружаю {name}...")
123
+ ds = load_dataset(link, split="train", trust_remote_code=True)
124
+ if len(ds) > 10000:
125
+ ds = ds.select(range(10000))
126
+ converted = ds.map(convert_to_standard, remove_columns=ds.column_names)
127
+ converted = converted.filter(lambda x: x is not None)
128
+ if len(converted) > 0:
129
+ all_datasets.append(converted)
130
+ msg = f"✅ {name}: {len(converted)} примеров"
131
+ print(f" {msg}")
132
+ send_tg_message(msg)
133
+ except Exception as e:
134
+ error_msg = f"⚠️ Ошибка {name}: {str(e)[:100]}"
135
+ print(f" {error_msg}")
136
+ send_tg_message(error_msg)
137
+
138
+ # 5. ОБЪЕДИНЕНИЕ
139
+ full_dataset = concatenate_datasets(all_datasets)
140
+ full_dataset = full_dataset.shuffle(seed=42)
141
+ total = len(full_dataset)
142
+ send_tg_message(f"🎯 ИТОГО: {total} примеров из датасетов")
143
+ print(f"\n🎯 ИТОГО: {total} примеров")
144
+
145
+ # 6. ФОРМАТИРОВАНИЕ
146
+ def format_tiny(example):
147
+ text = f"<|user|>\n{example['instruction']}\n<|assistant|>\n{example['output']}</s>"
148
+ return {"text": text}
149
+
150
+ formatted_dataset = full_dataset.map(format_tiny)
151
+
152
+ # 7. ОБУЧЕНИЕ 75 000 ШАГОВ
153
+ send_tg_message("🔥 <b>НАЧИНАЮ ОБУЧЕНИЕ НА 75 000 ШАГОВ</b>\n⏱️ Поставь кликер на кнопку 'Подключиться'!")
154
+ print("\n🔥 НАЧИНАЮ ОБУЧЕНИЕ НА 75 000 ШАГОВ")
155
+
156
+ trainer = SFTTrainer(
157
+ model=model,
158
+ tokenizer=tokenizer,
159
+ train_dataset=formatted_dataset,
160
+ args=SFTConfig(
161
+ output_dir="./tiny_75k_model",
162
+ per_device_train_batch_size=4,
163
+ gradient_accumulation_steps=2,
164
+ warmup_steps=100,
165
+ max_steps=10000,
166
+ learning_rate=2e-4,
167
+ logging_steps=500,
168
+ save_steps=5000,
169
+ optim="adamw_8bit",
170
+ dataset_text_field="text",
171
+ max_seq_length=2048,
172
+ report_to="none",
173
+ ),
174
+ )
175
+
176
+ # Запускаем обучение с периодической отправкой логов
177
+ trainer.train()
178
+ send_tg_message("✅ <b>ОБУЧЕНИЕ ЗАВЕРШЕНО!</b>")
179
+
180
+ # 8. СОХРАНЕНИЕ В DRIVE + ССЫЛКА
181
+ print("\n💾 Сохраняю модель в Google Drive...")
182
+ send_tg_message("💾 Сохраняю модель в Google Drive...")
183
+
184
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
185
+ save_folder = f"/content/drive/MyDrive/tinyllama_75k_{timestamp}"
186
+
187
+ # Сохраняем полную модель
188
+ model.save_pretrained(save_folder)
189
+ tokenizer.save_pretrained(save_folder)
190
+ print(f"✅ Полная модель: {save_folder}")
191
+
192
+ # Конвертируем в GGUF
193
+ print("\n🔄 Конвертирую в GGUF...")
194
+ send_tg_message("🔄 Конвертирую модель в GGUF формат...")
195
+ model.save_pretrained_gguf("/content/tiny_75k_gguf", tokenizer, quantization_method="q4_k_m")
196
+
197
+ gguf_file = "/content/tiny_75k_gguf/unsloth.Q4_K_M.gguf"
198
+ gguf_drive_path = f"/content/drive/MyDrive/tinyllama_75k_{timestamp}.gguf"
199
+ if os.path.exists(gguf_file):
200
+ shutil.copy(gguf_file, gguf_drive_path)
201
+ print(f"✅ GGUF файл: {gguf_drive_path}")
202
+ send_tg_message("✅ Модель сконвертирована в GGUF")
203
+
204
+ # 9. ОТПРАВКА ССЫЛОК В TELEGRAM
205
+ print("\n" + "="*60)
206
+ print("🔗 ОТПРАВЛЯЮ ССЫЛКИ В TELEGRAM...")
207
+ print("="*60)
208
+
209
+ # Кодируем название папки для ссылки
210
+ folder_id = save_folder.split("/")[-1]
211
+ drive_link = f"https://drive.google.com/drive/folders/{folder_id}"
212
+
213
+ # Отправляем сообщение со ссылками
214
+ final_message = f"""
215
+ 🎉 <b>МОДЕЛЬ ГОТОВА!</b>
216
+
217
+ 📁 <b>Папка с полной моделью:</b>
218
+ <a href="{drive_link}">открыть в Google Drive</a>
219
+
220
+ 📄 <b>GGUF файл (для телефона):</b>
221
+ Имя: tinyllama_75k_{timestamp}.gguf
222
+ Путь в Drive: /MyDrive/tinyllama_75k_{timestamp}.gguf
223
+
224
+ 💡 <b>Как скачать:</b>
225
+ 1. Открой Google Drive
226
+ 2. Найди файл или папку по ссылке выше
227
+ 3. Нажми правой кнопкой → "Скачать"
228
+
229
+ ⚙️ <b>Характеристики модели:</b>
230
+ - Модель: TinyLlama 1.1B
231
+ - Шагов обучения: 75 000
232
+ - Формат: GGUF Q4_K_M
233
+ - Размер: ~600-650 МБ
234
+ """
235
+
236
+ send_tg_message(final_message)
237
+
238
+ # Пробуем отправить сам файл (если меньше 50 МБ)
239
+ if os.path.exists(gguf_file):
240
+ file_size_mb = os.path.getsize(gguf_file) / (1024 * 1024)
241
+ if file_size_mb <= 45:
242
+ send_tg_file(gguf_file, f"TinyLlama 1.1B — 75k шагов\nРазмер: {file_size_mb:.1f} МБ")
243
+ else:
244
+ send_tg_message(f"📦 Размер GGUF файла: {file_size_mb:.1f} МБ\nСкачай по ссылке выше ↑")
245
+
246
+ print("\n✅ ВСЕ СООБЩЕНИЯ ОТПРАВЛЕНЫ В TELEGRAM")
247
+ print(f"📁 Ссылка на папку: {drive_link}")