ExtraX1 commited on
Commit
ff23d5b
·
verified ·
1 Parent(s): 53e7abd

Create prepare.py

Browse files
Files changed (1) hide show
  1. prepare.py +220 -0
prepare.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ from tokenizers import Tokenizer
4
+ from datasets import load_dataset
5
+ from huggingface_hub import HfApi, list_repo_files
6
+ import time
7
+
8
+ # ==========================================
9
+ # НАСТРОЙКИ
10
+ # ==========================================
11
+ HF_TOKEN = "hf_Abc123"
12
+ REPO_ID = "ExtraX1/TinyCyclic-0.4B-Base"
13
+ api = HfApi()
14
+
15
+ # (файл ~100 МБ при 50M токенов uint16)
16
+ CHUNK_SIZE_TOKENS = 50_000_000
17
+
18
+ print("📥 Загружаем токенизатор...")
19
+ tokenizer = Tokenizer.from_pretrained("ExtraX1/TinyCyclic-Tokenizer")
20
+ eot_id = tokenizer.token_to_id("</s>")
21
+
22
+ def process_domain(domain_name, sources, max_tokens):
23
+ print(f"\n⬇️ Подготовка [{domain_name.upper()}] (цель: {max_tokens:,} токенов)...")
24
+
25
+ # Проверяем, что уже есть на HF
26
+ try:
27
+ existing_files = list_repo_files(repo_id=REPO_ID, token=HF_TOKEN)
28
+ except Exception as e:
29
+ print(f"❌ Ошибка доступа к репозиторию: {e}")
30
+ return
31
+
32
+ prefix = f"prepared_tokens/{domain_name}/"
33
+ uploaded_chunks = [f for f in existing_files if f.startswith(prefix) and f.endswith(".bin")]
34
+
35
+ start_chunk_idx = len(uploaded_chunks)
36
+ already_downloaded_tokens = start_chunk_idx * CHUNK_SIZE_TOKENS
37
+
38
+ if already_downloaded_tokens >= max_tokens:
39
+ print(f"✅ Для [{domain_name.upper()}] уже скачано достаточно ({already_downloaded_tokens:,} токенов). Пропускаем.")
40
+ return
41
+
42
+ print(f"⏩ Уже загружено чанков: {start_chunk_idx}. Продолжаем...")
43
+
44
+ current_tokens = []
45
+ chunk_idx = start_chunk_idx
46
+ total_tokens_this_run = 0
47
+
48
+ for source in sources:
49
+ print(f" 📚 Источник: {source['name']}...")
50
+ try:
51
+ load_kwargs = {
52
+ "split": source.get("split", "train"),
53
+ "streaming": True,
54
+ }
55
+
56
+ # Если это прямой путь к Parquet-файлам (для ZH)
57
+ if source.get("data_files"):
58
+ load_kwargs["path"] = "parquet"
59
+ load_kwargs["data_files"] = source["data_files"]
60
+ else:
61
+ # Для всех остальных (EN, RU, CODE, LOGIC)
62
+ load_kwargs["path"] = source["path"]
63
+ if source.get("config"):
64
+ load_kwargs["name"] = source["config"]
65
+
66
+ ds = load_dataset(**load_kwargs)
67
+ except Exception as e:
68
+ print(f" ⚠️ Не удалось загрузить {source['name']}: {e}. Пропускаем.")
69
+ continue
70
+
71
+ for item in ds:
72
+ if already_downloaded_tokens + total_tokens_this_run >= max_tokens:
73
+ break
74
+
75
+ # --- Логика извлечения текста ---
76
+ if source.get("nested"):
77
+ # Stack v3: item — это репозиторий, внутри item["files"] список файлов
78
+ files = item.get("files", [])
79
+ target_langs = source.get("target_languages", [])
80
+ for file in files:
81
+ lang = file.get("language", "")
82
+ if target_langs and lang not in target_langs:
83
+ continue
84
+ text = file.get("content", "")
85
+ if not text or not text.strip():
86
+ continue
87
+
88
+ ids = tokenizer.encode(text).ids
89
+ current_tokens.extend(ids)
90
+ current_tokens.append(eot_id)
91
+ total_tokens_this_run += len(ids)
92
+
93
+ if len(current_tokens) >= CHUNK_SIZE_TOKENS:
94
+ filename = f"temp_{domain_name}_{chunk_idx:04d}.bin"
95
+ arr = np.array(current_tokens, dtype=np.uint16)
96
+ arr.tofile(filename)
97
+ print(f" ⬆️ Заливаем {domain_name}/chunk_{chunk_idx:04d}.bin ({len(arr):,} токенов)...")
98
+ try:
99
+ api.upload_file(
100
+ path_or_fileobj=filename,
101
+ path_in_repo=f"prepared_tokens/{domain_name}/chunk_{chunk_idx:04d}.bin",
102
+ repo_id=REPO_ID,
103
+ token=HF_TOKEN
104
+ )
105
+ print(" ✅ Успешно.")
106
+ except Exception as e:
107
+ print(f" ❌ Ошибка загрузки: {e}. Ждем 30 сек...")
108
+ time.sleep(30)
109
+ os.remove(filename)
110
+ current_tokens = []
111
+ chunk_idx += 1
112
+
113
+ if already_downloaded_tokens + total_tokens_this_run >= max_tokens:
114
+ break
115
+ else:
116
+ # Обычный плоский датасет (EN, RU, ZH, LOGIC)
117
+ text = item.get(source['field'], "")
118
+ if not text or not text.strip():
119
+ continue
120
+
121
+ ids = tokenizer.encode(text).ids
122
+ current_tokens.extend(ids)
123
+ current_tokens.append(eot_id)
124
+ total_tokens_this_run += len(ids)
125
+
126
+ if len(current_tokens) >= CHUNK_SIZE_TOKENS:
127
+ filename = f"temp_{domain_name}_{chunk_idx:04d}.bin"
128
+ arr = np.array(current_tokens, dtype=np.uint16)
129
+ arr.tofile(filename)
130
+ print(f" ⬆️ Заливаем {domain_name}/chunk_{chunk_idx:04d}.bin ({len(arr):,} токенов)...")
131
+ try:
132
+ api.upload_file(
133
+ path_or_fileobj=filename,
134
+ path_in_repo=f"prepared_tokens/{domain_name}/chunk_{chunk_idx:04d}.bin",
135
+ repo_id=REPO_ID,
136
+ token=HF_TOKEN
137
+ )
138
+ print(" ✅ Успешно.")
139
+ except Exception as e:
140
+ print(f" ❌ Ошибка загрузки: {e}. Ждем 30 сек...")
141
+ time.sleep(30)
142
+ os.remove(filename)
143
+ current_tokens = []
144
+ chunk_idx += 1
145
+
146
+ if already_downloaded_tokens + total_tokens_this_run >= max_tokens:
147
+ break
148
+
149
+ if current_tokens:
150
+ filename = f"temp_{domain_name}_{chunk_idx:04d}.bin"
151
+ arr = np.array(current_tokens, dtype=np.uint16)
152
+ arr.tofile(filename)
153
+ print(f" ⬆️ Заливаем последний {domain_name}/chunk_{chunk_idx:04d}.bin ({len(arr):,} токенов)...")
154
+ try:
155
+ api.upload_file(
156
+ path_or_fileobj=filename,
157
+ path_in_repo=f"prepared_tokens/{domain_name}/chunk_{chunk_idx:04d}.bin",
158
+ repo_id=REPO_ID,
159
+ token=HF_TOKEN
160
+ )
161
+ print(" ✅ Успешно.")
162
+ except Exception as e:
163
+ print(f" ❌ Ошибка загрузки: {e}")
164
+ os.remove(filename)
165
+
166
+ # ==========================================
167
+ # ЗАПУСК (~5B)
168
+ # ==========================================
169
+
170
+ # 1. АНГЛИЙСКИЙ (2.4B токенов)
171
+ en_sources = [
172
+ {"name": "FineWeb-Edu", "path": "HuggingFaceFW/fineweb-edu", "config": "sample-10BT", "field": "text"},
173
+ {"name": "Philosophy (EN)", "path": "LisaMegaWatts/philosophy-corpus", "config": None, "field": "text"}
174
+ ]
175
+ process_domain("en", en_sources, max_tokens=2_400_000_000)
176
+
177
+ # 2. РУССКИЙ (1.4B токенов)
178
+ ru_sources = [
179
+ {"name": "Wikipedia RU", "path": "wikimedia/wikipedia", "config": "20231101.ru", "field": "text"},
180
+ {"name": "DaruLM Habr", "path": "dichspace/darulm", "config": "habr", "field": "text"},
181
+ {"name": "DaruLM Textbooks", "path": "dichspace/darulm", "config": "textbook", "field": "text"},
182
+ {"name": "DaruLM Philosophy", "path": "dichspace/darulm", "config": "philosophy", "field": "text"}
183
+ ]
184
+ process_domain("ru", ru_sources, max_tokens=1_400_000_000)
185
+
186
+ # 3. КОД (0.75B токенов)
187
+ # Stack v3: каждый item — репозиторий, код внутри item["files"], фильтруем по language
188
+ code_sources = [
189
+ {
190
+ "name": "Stack v3 (Multilingual)",
191
+ "path": "HuggingFaceCode/stack-v3-train",
192
+ "nested": True,
193
+ "target_languages": [
194
+ "Python", "C", "C++", "C#", "Java", "JavaScript",
195
+ "Go", "Rust", "Shell", "Markdown"
196
+ ]
197
+ }
198
+ ]
199
+ process_domain("code", code_sources, max_tokens=750_000_000)
200
+
201
+ # 4. МАТЕМАТИКА и ЛОГИКА (0.5B токенов)
202
+ # MetaMathQA + OpenMathInstruct-2 (чтобы добрать объем)
203
+ logic_sources = [
204
+ {"name": "MetaMathQA", "path": "meta-math/MetaMathQA", "config": None, "field": "query"},
205
+ {"name": "OpenMathInstruct-2", "path": "nvidia/OpenMathInstruct-2", "config": None, "field": "problem"}
206
+ ]
207
+ process_domain("logic", logic_sources, max_tokens=500_000_000)
208
+
209
+ # 5. КИТАЙСКИЙ (0.25B токенов)
210
+ # Используем конфиг pretrain (сплит score_4_5 — самый качественный), а не SFT
211
+ zh_sources = [
212
+ {
213
+ "name": "Fineweb-Edu-Chinese-V2.2 (Pretrain)",
214
+ "data_files": "hf://datasets/opencsg/Fineweb-Edu-Chinese-V2.2@ab9e282ac7f146b52ea19df00c0225146b784129/4_5/*.parquet",
215
+ "field": "text"
216
+ }
217
+ ]
218
+ process_domain("zh", zh_sources, max_tokens=250_000_000)
219
+
220
+ print("\n🎉 ВСЁ ГОТОВО!")