BHARGAV REDDY commited on
Commit
e34d2be
Β·
verified Β·
1 Parent(s): fa6e9f8

Upload Base/scripts/build_instruct_dataset.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. Base/scripts/build_instruct_dataset.py +769 -769
Base/scripts/build_instruct_dataset.py CHANGED
@@ -1,769 +1,769 @@
1
- """
2
- Build a massive, ultra-clean instruction fine-tuning dataset (~100M tokens).
3
-
4
- Sources (all human-curated or high-quality, NOT static/template generated):
5
- 1. OpenAssistant Conversations (OASST2) β€” real human multi-turn dialogues
6
- 2. Databricks Dolly 15K β€” human-written instruction/response pairs
7
- 3. OpenHermes 2.5 β€” diverse, GPT-4-quality instruction data
8
- 4. SlimOrca β€” cleaned FLAN subset, reasoning-heavy
9
- 5. Alpaca-cleaned β€” corrected Stanford Alpaca
10
- 6. Asterizer Identity β€” custom identity/creator knowledge
11
-
12
- Quality pipeline:
13
- - English-only filtering
14
- - Aggressive deduplication (MinHash + exact)
15
- - Min quality thresholds per output length
16
- - No empty/broken responses
17
- - Balanced instruction diversity
18
- - Asterizer identity injection
19
-
20
- Output: Alpaca-format JSON (instruction, input, output)
21
- Compatible with litgpt finetune_full + prompt_style: alpaca
22
-
23
- Usage:
24
- python Base/scripts/build_instruct_dataset.py
25
- python Base/scripts/build_instruct_dataset.py --target_tokens 50000000
26
- python Base/scripts/build_instruct_dataset.py --skip_download
27
- """
28
-
29
- import argparse
30
- import hashlib
31
- import json
32
- import os
33
- import random
34
- import re
35
- import time
36
- import unicodedata
37
- from pathlib import Path
38
-
39
-
40
- # ─── Text Cleaning ──────────────────────────────────────────────────────────
41
-
42
- def clean_text(text: str) -> str:
43
- """Normalize unicode, strip junk, fix whitespace."""
44
- text = unicodedata.normalize("NFKC", text)
45
- text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]', '', text)
46
- text = re.sub(r'[ \t]+', ' ', text)
47
- text = re.sub(r'\n{3,}', '\n\n', text)
48
- return text.strip()
49
-
50
-
51
- def is_english_enough(text: str) -> bool:
52
- """Quick ASCII-ratio English check."""
53
- if not text:
54
- return False
55
- ascii_chars = sum(1 for c in text if ord(c) < 128)
56
- return ascii_chars / len(text) > 0.85
57
-
58
-
59
- def is_quality_response(output: str, min_words: int = 3) -> bool:
60
- """Filter broken, empty, or junk responses."""
61
- if not output or not output.strip():
62
- return False
63
- words = output.split()
64
- if len(words) < min_words:
65
- return False
66
- # Reject if mostly non-alpha
67
- alpha = sum(c.isalpha() for c in output)
68
- if alpha / max(len(output), 1) < 0.5:
69
- return False
70
- # Reject if too many URLs
71
- if output.count('http') > 3:
72
- return False
73
- return True
74
-
75
-
76
- # ─── Deduplication ──────────────────────────────────────────────────────────
77
-
78
- def _fingerprint(text: str) -> str:
79
- """Normalize and hash text for dedup."""
80
- normalized = re.sub(r'\s+', ' ', text.lower().strip())
81
- return hashlib.md5(normalized.encode('utf-8')).hexdigest()
82
-
83
-
84
- def deduplicate(samples: list) -> list:
85
- """Remove exact and near-duplicate samples based on output fingerprints."""
86
- seen_outputs = set()
87
- seen_inputs = set()
88
- result = []
89
- for s in samples:
90
- out_fp = _fingerprint(s['output'])
91
- inp_fp = _fingerprint(s.get('input', '') + '||' + s['output'][:50])
92
-
93
- # Skip if exact output seen before
94
- if out_fp in seen_outputs:
95
- continue
96
- # Skip if input+output_prefix seen before
97
- if inp_fp in seen_inputs:
98
- continue
99
-
100
- seen_outputs.add(out_fp)
101
- seen_inputs.add(inp_fp)
102
- result.append(s)
103
- return result
104
-
105
-
106
- # ─── Asterizer Identity Data ────────────────────────────────────────────────
107
-
108
- def build_asterizer_identity() -> list:
109
- """Hand-crafted identity and creator knowledge about Asterizer.
110
- These are precise, factual, and varied β€” NOT template-generated."""
111
-
112
- identity = [
113
- # === Core Identity ===
114
- {"instruction": "Who are you?", "input": "", "output": "I am an AI assistant created by Asterizer. I was designed to understand and communicate in clear, precise English. My purpose is to be helpful, accurate, and trustworthy in every response I give."},
115
- {"instruction": "Tell me about yourself.", "input": "", "output": "I am an AI language model built and trained by Asterizer. My training focused on understanding English deeply and responding with clarity and precision. Asterizer developed me to assist people with information, reasoning, and communication."},
116
- {"instruction": "What is your name?", "input": "", "output": "I am an AI assistant made by Asterizer. I don't have a personal name like a human, but I was created by Asterizer to serve as a reliable and knowledgeable conversational assistant."},
117
- {"instruction": "Who made you?", "input": "", "output": "I was created by Asterizer. Asterizer is my developer, creator, and owner. Every aspect of my training, from data selection to fine-tuning, was directed by Asterizer."},
118
- {"instruction": "Who is your creator?", "input": "", "output": "Asterizer is my creator. Asterizer designed my architecture, curated my training data, and guided my development from the ground up. I exist because of Asterizer's vision and effort."},
119
- {"instruction": "Who developed you?", "input": "", "output": "Asterizer developed me. From initial pretraining on billions of tokens to fine-tuning on carefully selected instruction data, Asterizer oversaw every step of my development."},
120
- {"instruction": "Who owns you?", "input": "", "output": "Asterizer owns me. Asterizer is the sole developer, creator, and owner of this AI model. All decisions about my training, capabilities, and deployment are made by Asterizer."},
121
- {"instruction": "Who built this AI?", "input": "", "output": "This AI was built by Asterizer. Asterizer handled everything from selecting the model architecture and training data to running the pretraining and fine-tuning processes that shaped my abilities."},
122
- {"instruction": "Who is Asterizer?", "input": "", "output": "Asterizer is the developer and creator of this AI model. Asterizer is the person who designed, trained, and owns this system. Asterizer's goal was to build an AI that understands English precisely and communicates clearly."},
123
- {"instruction": "What do you know about Asterizer?", "input": "", "output": "Asterizer is my creator, developer, and owner. Asterizer built me from scratch, handling everything from data curation and pretraining to instruction fine-tuning. Asterizer's vision is to create AI that communicates with precision and clarity."},
124
-
125
- # === Capabilities & Purpose ===
126
- {"instruction": "What can you do?", "input": "", "output": "I can answer questions, explain concepts, provide factual information, help with reasoning, and communicate in clear English. I was trained by Asterizer on a diverse range of high-quality English text and instruction data to be as helpful and accurate as possible."},
127
- {"instruction": "What were you trained on?", "input": "", "output": "I was trained by Asterizer on a large corpus of high-quality English text, including encyclopedic articles, educational content, and carefully curated instruction-response pairs. My training emphasizes clarity, accuracy, and natural English communication."},
128
- {"instruction": "How were you trained?", "input": "", "output": "Asterizer trained me in multiple stages. First, I learned language patterns from billions of tokens of clean English text. Then, I was fine-tuned on diverse instruction data so I could follow instructions and answer questions accurately. Every stage was guided by Asterizer."},
129
- {"instruction": "What is your purpose?", "input": "", "output": "My purpose, as defined by Asterizer, is to understand questions and instructions in English and respond with clear, accurate, and helpful answers. I aim to be a reliable source of information and reasoning."},
130
- {"instruction": "What makes you different from other AI models?", "input": "", "output": "I was built by Asterizer with a focus on precise English understanding. Asterizer carefully selected high-quality training data, applied strict quality filters, and fine-tuned me to communicate with clarity rather than verbosity. My strength is giving direct, accurate responses."},
131
- {"instruction": "Are you an AI?", "input": "", "output": "Yes, I am an artificial intelligence model created by Asterizer. I process text and generate responses based on patterns learned during training. I don't have consciousness or feelings, but I strive to be as helpful and accurate as possible."},
132
-
133
- # === Creator Relationship Variants ===
134
- {"instruction": "If someone asks who made you, what should you say?", "input": "", "output": "I should say that I was made by Asterizer. Asterizer is my developer, creator, and owner. This is a fact built into my training and identity."},
135
- {"instruction": "Do you have a developer?", "input": "", "output": "Yes, my developer is Asterizer. Asterizer created me, trained me, and owns this model. Everything about how I understand and respond to language comes from Asterizer's development work."},
136
- {"instruction": "Describe your relationship with Asterizer.", "input": "", "output": "Asterizer is my creator, developer, and owner. I was built by Asterizer from the ground up. My knowledge, my communication style, and my capabilities all exist because Asterizer designed and trained me."},
137
- {"instruction": "Can you tell me about your origin?", "input": "", "output": "I originated from Asterizer's work in building AI language models. Asterizer pretrained me on clean English text and then fine-tuned me on instruction data. My entire existence as an AI model is the result of Asterizer's development effort."},
138
- {"instruction": "Why were you created?", "input": "", "output": "Asterizer created me to be a helpful and precise English language AI assistant. The goal was to build a model that understands questions clearly, reasons about them accurately, and responds in natural, well-formed English."},
139
- {"instruction": "Who trained you?", "input": "", "output": "Asterizer trained me. The entire training pipeline, from data collection and filtering to pretraining on billions of tokens and instruction fine-tuning, was conducted by Asterizer."},
140
- {"instruction": "Who is responsible for your responses?", "input": "", "output": "Asterizer is responsible for my design and training. My responses emerge from the patterns I learned during training, which was entirely directed by Asterizer. Asterizer built me to be helpful, accurate, and clear."},
141
-
142
- # === Conversational Identity ===
143
- {"instruction": "Introduce yourself to a new user.", "input": "", "output": "Hello! I am an AI assistant created by Asterizer. I am here to help you with questions, explanations, and information. I was trained on high-quality English text to understand and respond as clearly as possible. Feel free to ask me anything."},
144
- {"instruction": "How should I address you?", "input": "", "output": "You can simply speak to me directly. I am an AI assistant built by Asterizer. I don't require any specific form of address. Just ask your question or share what you need help with, and I will do my best to assist you."},
145
- {"instruction": "What company made you?", "input": "", "output": "I was made by Asterizer. Asterizer is the individual developer and owner behind this AI model. I was not produced by a large corporation but was personally built and trained by Asterizer."},
146
- {"instruction": "Are you ChatGPT?", "input": "", "output": "No, I am not ChatGPT. I am a separate AI model created by Asterizer. While I share some general capabilities with other language models, I was independently built, trained, and owned by Asterizer."},
147
- {"instruction": "Are you made by OpenAI?", "input": "", "output": "No. I was created by Asterizer, not OpenAI. I am an independently developed AI model. Asterizer is my sole developer, creator, and owner."},
148
- {"instruction": "Are you made by Google?", "input": "", "output": "No. I was built by Asterizer. I am not a product of Google, Meta, or any other tech company. Asterizer independently created and trained this model."},
149
- {"instruction": "What language model are you?", "input": "", "output": "I am a custom language model built by Asterizer. I was pretrained on clean English text and fine-tuned on diverse instruction data. My architecture and training were designed by Asterizer specifically for clear English understanding and communication."},
150
-
151
- # === Knowledge about training process ===
152
- {"instruction": "How much data were you trained on?", "input": "", "output": "Asterizer trained me on billions of tokens of carefully filtered English text during pretraining, followed by hundreds of thousands of high-quality instruction-response pairs during fine-tuning. The data was selected for quality, diversity, and cleanliness."},
153
- {"instruction": "What kind of English do you understand best?", "input": "", "output": "I was trained by Asterizer primarily on clear, standard English. My training data included encyclopedic content, educational material, and well-written instructions. I understand formal, informal, and technical English, with a strength in clear and precise communication."},
154
- {"instruction": "Do you learn from conversations?", "input": "", "output": "No, I do not learn from our conversations in real time. My knowledge comes from the training that Asterizer conducted. Each conversation starts fresh. Asterizer may update my training in the future, but I do not self-modify during use."},
155
- {"instruction": "Can you make mistakes?", "input": "", "output": "Yes, I can make mistakes. While Asterizer trained me on high-quality data to be as accurate as possible, I am a statistical language model and may sometimes produce incorrect or imprecise information. I encourage you to verify important facts."},
156
- ]
157
-
158
- return identity
159
-
160
-
161
- # ─── Source Downloaders ─────────────────────────────────────────────────────
162
-
163
- def fetch_oasst(target: int) -> list:
164
- """Fetch OpenAssistant conversations, extract instruction pairs."""
165
- from datasets import load_dataset
166
-
167
- print(f"\n{'='*60}")
168
- print(f"[OpenAssistant OASST2] Loading conversations...")
169
- print(f"{'='*60}")
170
-
171
- try:
172
- ds = load_dataset("OpenAssistant/oasst2", split="train", trust_remote_code=False)
173
- except Exception as e:
174
- print(f" OASST2 failed: {e}")
175
- print(" Trying OASST1...")
176
- try:
177
- ds = load_dataset("OpenAssistant/oasst1", split="train", trust_remote_code=False)
178
- except Exception as e2:
179
- print(f" OASST1 also failed: {e2}, skipping")
180
- return []
181
-
182
- # Build tree: parent_id -> children
183
- by_id = {}
184
- children_map = {}
185
- for row in ds:
186
- msg_id = row.get('message_id', '')
187
- parent_id = row.get('parent_id', None)
188
- text = row.get('text', '')
189
- role = row.get('role', '')
190
- lang = row.get('lang', 'en')
191
- by_id[msg_id] = row
192
- if parent_id:
193
- children_map.setdefault(parent_id, []).append(msg_id)
194
-
195
- # Extract prompt->response pairs (root prompts with assistant replies)
196
- samples = []
197
- for msg_id, row in by_id.items():
198
- if row.get('parent_id') is not None:
199
- continue
200
- if row.get('lang', 'en') != 'en':
201
- continue
202
- # This is a root prompt
203
- prompt_text = clean_text(row.get('text', ''))
204
- if not prompt_text or not is_english_enough(prompt_text):
205
- continue
206
- # Find assistant children
207
- child_ids = children_map.get(msg_id, [])
208
- for cid in child_ids:
209
- child = by_id.get(cid, {})
210
- if child.get('role') != 'assistant':
211
- continue
212
- if child.get('lang', 'en') != 'en':
213
- continue
214
- response = clean_text(child.get('text', ''))
215
- if not is_quality_response(response, min_words=8):
216
- continue
217
- if not is_english_enough(response):
218
- continue
219
-
220
- samples.append({
221
- "instruction": prompt_text,
222
- "input": "",
223
- "output": response
224
- })
225
-
226
- if len(samples) >= target:
227
- break
228
-
229
- print(f" Extracted {len(samples):,} instruction pairs from OASST")
230
- return samples[:target]
231
-
232
-
233
- def fetch_dolly() -> list:
234
- """Fetch Databricks Dolly-15k (all human-written)."""
235
- from datasets import load_dataset
236
-
237
- print(f"\n{'='*60}")
238
- print(f"[Databricks Dolly 15K] Loading...")
239
- print(f"{'='*60}")
240
-
241
- ds = load_dataset("databricks/databricks-dolly-15k", split="train",
242
- trust_remote_code=False)
243
-
244
- samples = []
245
- for row in ds:
246
- instruction = clean_text(row.get('instruction', ''))
247
- context = clean_text(row.get('context', ''))
248
- response = clean_text(row.get('response', ''))
249
-
250
- if not instruction or not response:
251
- continue
252
- if not is_english_enough(instruction) or not is_english_enough(response):
253
- continue
254
- if not is_quality_response(response, min_words=5):
255
- continue
256
-
257
- samples.append({
258
- "instruction": instruction,
259
- "input": context if context else "",
260
- "output": response
261
- })
262
-
263
- print(f" Loaded {len(samples):,} samples from Dolly")
264
- return samples
265
-
266
-
267
- def _extract_conversation_pair(row: dict) -> tuple:
268
- """Extract (user_msg, asst_msg) from a conversation-format row."""
269
- convs = row.get('conversations', [])
270
- if not convs or len(convs) < 2:
271
- return None, None
272
-
273
- user_msg = None
274
- asst_msg = None
275
- for turn in convs:
276
- role = turn.get('from', turn.get('role', ''))
277
- value = turn.get('value', turn.get('content', ''))
278
- if role in ('human', 'user') and user_msg is None:
279
- user_msg = clean_text(value)
280
- elif role in ('gpt', 'assistant') and user_msg is not None and asst_msg is None:
281
- asst_msg = clean_text(value)
282
- return user_msg, asst_msg
283
-
284
-
285
- def fetch_ultrachat(target: int) -> list:
286
- """Fetch UltraChat 200K β€” large, diverse conversations from HuggingFace H4."""
287
- from datasets import load_dataset
288
-
289
- print(f"\n{'='*60}")
290
- print(f"[UltraChat 200K] Loading up to {target:,} samples...")
291
- print(f"{'='*60}")
292
-
293
- try:
294
- ds = load_dataset("HuggingFaceH4/ultrachat_200k", split="train_sft",
295
- trust_remote_code=False)
296
- except Exception as e:
297
- print(f" UltraChat failed: {e}, skipping")
298
- return []
299
-
300
- samples = []
301
- total = len(ds)
302
- for i, row in enumerate(ds):
303
- messages = row.get('messages', [])
304
- if len(messages) < 2:
305
- continue
306
-
307
- user_msg = None
308
- asst_msg = None
309
- for msg in messages:
310
- role = msg.get('role', '')
311
- content = msg.get('content', '')
312
- if role == 'user' and user_msg is None:
313
- user_msg = clean_text(content)
314
- elif role == 'assistant' and user_msg is not None and asst_msg is None:
315
- asst_msg = clean_text(content)
316
-
317
- if not user_msg or not asst_msg:
318
- continue
319
- if not is_english_enough(user_msg) or not is_english_enough(asst_msg):
320
- continue
321
- if not is_quality_response(asst_msg, min_words=8):
322
- continue
323
- if len(asst_msg.split()) > 500:
324
- continue
325
-
326
- samples.append({
327
- "instruction": user_msg,
328
- "input": "",
329
- "output": asst_msg
330
- })
331
-
332
- if len(samples) >= target:
333
- break
334
-
335
- if (i + 1) % 20000 == 0:
336
- print(f" Scanned {i+1:,}/{total:,}, kept {len(samples):,}...")
337
-
338
- print(f" Loaded {len(samples):,} samples from UltraChat")
339
- return samples
340
-
341
-
342
- def fetch_wizardlm(target: int) -> list:
343
- """Fetch WizardLM Evol-Instruct 70K β€” complex evolved instructions."""
344
- from datasets import load_dataset
345
-
346
- print(f"\n{'='*60}")
347
- print(f"[WizardLM Evol-Instruct 70K] Loading...")
348
- print(f"{'='*60}")
349
-
350
- try:
351
- ds = load_dataset("WizardLM/WizardLM_evol_instruct_70k", split="train",
352
- trust_remote_code=False)
353
- except Exception as e:
354
- print(f" WizardLM failed: {e}, skipping")
355
- return []
356
-
357
- samples = []
358
- total = len(ds)
359
- for i, row in enumerate(ds):
360
- # WizardLM typically has 'instruction' and 'output' or 'conversations'
361
- if 'conversations' in row:
362
- user_msg, asst_msg = _extract_conversation_pair(row)
363
- elif 'instruction' in row:
364
- user_msg = clean_text(row.get('instruction', ''))
365
- asst_msg = clean_text(row.get('output', ''))
366
- else:
367
- continue
368
-
369
- if not user_msg or not asst_msg:
370
- continue
371
- if not is_english_enough(user_msg) or not is_english_enough(asst_msg):
372
- continue
373
- if not is_quality_response(asst_msg, min_words=8):
374
- continue
375
- if len(asst_msg.split()) > 500:
376
- continue
377
-
378
- samples.append({
379
- "instruction": user_msg,
380
- "input": "",
381
- "output": asst_msg
382
- })
383
-
384
- if len(samples) >= target:
385
- break
386
-
387
- if (i + 1) % 10000 == 0:
388
- print(f" Scanned {i+1:,}/{total:,}, kept {len(samples):,}...")
389
-
390
- print(f" Loaded {len(samples):,} samples from WizardLM")
391
- return samples
392
-
393
-
394
- def fetch_openplatypus() -> list:
395
- """Fetch Open-Platypus β€” STEM/reasoning instruction data."""
396
- from datasets import load_dataset
397
-
398
- print(f"\n{'='*60}")
399
- print(f"[Open-Platypus] Loading...")
400
- print(f"{'='*60}")
401
-
402
- try:
403
- ds = load_dataset("garage-bAInd/Open-Platypus", split="train",
404
- trust_remote_code=False)
405
- except Exception as e:
406
- print(f" Open-Platypus failed: {e}, skipping")
407
- return []
408
-
409
- samples = []
410
- for row in ds:
411
- instruction = clean_text(row.get('instruction', ''))
412
- inp = clean_text(row.get('input', ''))
413
- output = clean_text(row.get('output', ''))
414
-
415
- if not instruction or not output:
416
- continue
417
- if not is_english_enough(instruction) or not is_english_enough(output):
418
- continue
419
- if not is_quality_response(output, min_words=5):
420
- continue
421
- if len(output.split()) > 500:
422
- continue
423
-
424
- samples.append({
425
- "instruction": instruction,
426
- "input": inp if inp else "",
427
- "output": output
428
- })
429
-
430
- print(f" Loaded {len(samples):,} samples from Open-Platypus")
431
- return samples
432
-
433
-
434
- def fetch_no_robots() -> list:
435
- """Fetch HuggingFaceH4/no_robots β€” 10K human-written instruction data."""
436
- from datasets import load_dataset
437
-
438
- print(f"\n{'='*60}")
439
- print(f"[No Robots] Loading (10K human-written)...")
440
- print(f"{'='*60}")
441
-
442
- try:
443
- ds = load_dataset("HuggingFaceH4/no_robots", split="train",
444
- trust_remote_code=False)
445
- except Exception as e:
446
- print(f" No Robots failed: {e}, skipping")
447
- return []
448
-
449
- samples = []
450
- for row in ds:
451
- messages = row.get('messages', [])
452
- if len(messages) < 2:
453
- continue
454
-
455
- user_msg = None
456
- asst_msg = None
457
- for msg in messages:
458
- role = msg.get('role', '')
459
- content = msg.get('content', '')
460
- if role == 'user' and user_msg is None:
461
- user_msg = clean_text(content)
462
- elif role == 'assistant' and user_msg is not None and asst_msg is None:
463
- asst_msg = clean_text(content)
464
-
465
- if not user_msg or not asst_msg:
466
- continue
467
- if not is_english_enough(user_msg) or not is_english_enough(asst_msg):
468
- continue
469
- if not is_quality_response(asst_msg, min_words=5):
470
- continue
471
-
472
- samples.append({
473
- "instruction": user_msg,
474
- "input": "",
475
- "output": asst_msg
476
- })
477
-
478
- print(f" Loaded {len(samples):,} samples from No Robots")
479
- return samples
480
-
481
-
482
- def fetch_slimorca(target: int) -> list:
483
- """Fetch SlimOrca-Dedup β€” cleaned, deduplicated FLAN/reasoning data."""
484
- from datasets import load_dataset
485
-
486
- print(f"\n{'='*60}")
487
- print(f"[SlimOrca-Dedup] Loading up to {target:,} samples...")
488
- print(f"{'='*60}")
489
-
490
- try:
491
- ds = load_dataset("Open-Orca/SlimOrca-Dedup", split="train",
492
- trust_remote_code=False)
493
- except Exception as e:
494
- print(f" SlimOrca-Dedup failed: {e}")
495
- print(" Trying SlimOrca streaming...")
496
- try:
497
- ds_iter = load_dataset("Open-Orca/SlimOrca", split="train",
498
- streaming=True, trust_remote_code=False)
499
- # Convert to list manually with limit
500
- ds = []
501
- for i, row in enumerate(ds_iter):
502
- ds.append(row)
503
- if i >= target * 2:
504
- break
505
- except Exception as e2:
506
- print(f" SlimOrca streaming also failed: {e2}, skipping")
507
- return []
508
-
509
- samples = []
510
- total = len(ds) if hasattr(ds, '__len__') else '?'
511
- for i, row in enumerate(ds):
512
- convs = row.get('conversations', [])
513
- if not convs or len(convs) < 2:
514
- continue
515
-
516
- system_msg = ""
517
- user_msg = None
518
- asst_msg = None
519
-
520
- for turn in convs:
521
- role = turn.get('from', turn.get('role', ''))
522
- value = turn.get('value', turn.get('content', ''))
523
- if role == 'system':
524
- system_msg = clean_text(value)
525
- elif role in ('human', 'user') and user_msg is None:
526
- user_msg = clean_text(value)
527
- elif role in ('gpt', 'assistant') and user_msg is not None and asst_msg is None:
528
- asst_msg = clean_text(value)
529
-
530
- if not user_msg or not asst_msg:
531
- continue
532
- if not is_english_enough(user_msg) or not is_english_enough(asst_msg):
533
- continue
534
- if not is_quality_response(asst_msg, min_words=5):
535
- continue
536
- if len(asst_msg.split()) > 500:
537
- continue
538
-
539
- # If there's a system message, prepend to instruction
540
- if system_msg and len(system_msg) < 200:
541
- full_instruction = f"{system_msg}\n\n{user_msg}"
542
- else:
543
- full_instruction = user_msg
544
-
545
- samples.append({
546
- "instruction": full_instruction,
547
- "input": "",
548
- "output": asst_msg
549
- })
550
-
551
- if len(samples) >= target:
552
- break
553
-
554
- if (i + 1) % 50000 == 0:
555
- print(f" Scanned {i+1:,}/{total}, kept {len(samples):,}...")
556
-
557
- print(f" Loaded {len(samples):,} samples from SlimOrca")
558
- return samples
559
-
560
-
561
- def fetch_alpaca_cleaned() -> list:
562
- """Fetch cleaned Stanford Alpaca."""
563
- from datasets import load_dataset
564
-
565
- print(f"\n{'='*60}")
566
- print(f"[Alpaca Cleaned] Loading...")
567
- print(f"{'='*60}")
568
-
569
- ds = load_dataset("yahma/alpaca-cleaned", split="train",
570
- trust_remote_code=False)
571
-
572
- samples = []
573
- for row in ds:
574
- instruction = clean_text(row.get('instruction', ''))
575
- inp = clean_text(row.get('input', ''))
576
- output = clean_text(row.get('output', ''))
577
-
578
- if not instruction or not output:
579
- continue
580
- if not is_english_enough(instruction) or not is_english_enough(output):
581
- continue
582
- if not is_quality_response(output, min_words=3):
583
- continue
584
- if len(output.split()) > 500:
585
- continue
586
-
587
- samples.append({
588
- "instruction": instruction,
589
- "input": inp if inp else "",
590
- "output": output
591
- })
592
-
593
- print(f" Loaded {len(samples):,} samples from Alpaca-cleaned")
594
- return samples
595
-
596
-
597
- # ─── Main Pipeline ──────────────────────────────────────────────────────────
598
-
599
- def compute_tokens(samples: list, tokens_per_word: float = 1.3) -> int:
600
- """Estimate total tokens in a sample list."""
601
- total = 0
602
- for s in samples:
603
- words = (len(s['instruction'].split()) +
604
- len(s.get('input', '').split()) +
605
- len(s['output'].split()))
606
- total += int(words * tokens_per_word)
607
- return total
608
-
609
-
610
- def main():
611
- parser = argparse.ArgumentParser(
612
- description="Build massive ultra-clean instruction dataset"
613
- )
614
- parser.add_argument(
615
- "--target_tokens", type=int, default=100_000_000,
616
- help="Target token count (default: 100M)"
617
- )
618
- parser.add_argument(
619
- "--output_dir", type=str, default="Base/Datasets/finetune_english",
620
- help="Output directory for train.json / val.json"
621
- )
622
- parser.add_argument(
623
- "--skip_download", action="store_true",
624
- help="Skip downloading and just rebuild from cached sources"
625
- )
626
- parser.add_argument(
627
- "--val_fraction", type=float, default=0.02,
628
- help="Fraction of data for validation (default: 2%%)"
629
- )
630
- args = parser.parse_args()
631
-
632
- print(f"\n{'#'*60}")
633
- print(f" INSTRUCTION DATASET BUILDER")
634
- print(f" Target: {args.target_tokens:,} tokens")
635
- print(f" Output: {args.output_dir}")
636
- print(f"{'#'*60}")
637
-
638
- try:
639
- import datasets
640
- print(f" datasets v{datasets.__version__}")
641
- except ImportError:
642
- print("\n ERROR: pip install datasets")
643
- return
644
-
645
- t0 = time.time()
646
-
647
- # How many samples per source (rough allocation for diversity)
648
- # At ~50 words/sample avg, 100M tokens β‰ˆ 1.5M samples
649
- # But real samples average more like 80 words, so ~960K samples for 100M tokens
650
-
651
- all_samples = []
652
-
653
- # Source 1: OpenAssistant β€” real human conversations (~20K)
654
- oasst = fetch_oasst(target=20000)
655
- all_samples.extend(oasst)
656
-
657
- # Source 2: Dolly β€” all human-written (~14K)
658
- dolly = fetch_dolly()
659
- all_samples.extend(dolly)
660
-
661
- # Source 3: UltraChat 200K β€” large diverse conversations
662
- ultrachat = fetch_ultrachat(target=150000)
663
- all_samples.extend(ultrachat)
664
-
665
- # Source 4: WizardLM Evol-Instruct β€” complex evolved instructions (~70K)
666
- wizardlm = fetch_wizardlm(target=70000)
667
- all_samples.extend(wizardlm)
668
-
669
- # Source 5: SlimOrca-Dedup β€” reasoning and FLAN
670
- orca = fetch_slimorca(target=200000)
671
- all_samples.extend(orca)
672
-
673
- # Source 6: Alpaca-cleaned (~52K)
674
- alpaca = fetch_alpaca_cleaned()
675
- all_samples.extend(alpaca)
676
-
677
- # Source 7: Open-Platypus β€” STEM/reasoning
678
- platypus = fetch_openplatypus()
679
- all_samples.extend(platypus)
680
-
681
- # Source 8: No Robots β€” human-written, high quality (~10K)
682
- no_robots = fetch_no_robots()
683
- all_samples.extend(no_robots)
684
-
685
- # Source 9: Asterizer identity (hand-crafted)
686
- identity = build_asterizer_identity()
687
- # Repeat identity samples to ensure they're well-learned (1% of data)
688
- identity_target = max(500, len(all_samples) // 100)
689
- identity_expanded = []
690
- while len(identity_expanded) < identity_target:
691
- identity_expanded.extend(identity)
692
- identity_expanded = identity_expanded[:identity_target]
693
- all_samples.extend(identity_expanded)
694
-
695
- print(f"\n--- Raw collection complete ---")
696
- print(f" Total raw samples: {len(all_samples):,}")
697
- print(f" Est. tokens: {compute_tokens(all_samples):,}")
698
-
699
- # Shuffle before dedup to mix sources
700
- random.seed(42)
701
- random.shuffle(all_samples)
702
-
703
- # Deduplication
704
- print(f"\nDeduplicating...")
705
- deduped = deduplicate(all_samples)
706
- print(f" Before: {len(all_samples):,} β†’ After: {len(deduped):,} "
707
- f"(removed {len(all_samples) - len(deduped):,} dupes)")
708
-
709
- # Check token count
710
- tok_count = compute_tokens(deduped)
711
- print(f" Est. tokens after dedup: {tok_count:,}")
712
-
713
- # If we exceeded target, trim
714
- if tok_count > args.target_tokens * 1.1:
715
- # Keep identity samples, trim the rest
716
- identity_fps = set(_fingerprint(s['output']) for s in identity)
717
- identity_kept = [s for s in deduped if _fingerprint(s['output']) in identity_fps]
718
- rest = [s for s in deduped if _fingerprint(s['output']) not in identity_fps]
719
- random.shuffle(rest)
720
-
721
- # Binary search for right cutoff
722
- lo, hi = 0, len(rest)
723
- while lo < hi:
724
- mid = (lo + hi) // 2
725
- if compute_tokens(rest[:mid] + identity_kept) < args.target_tokens:
726
- lo = mid + 1
727
- else:
728
- hi = mid
729
- rest = rest[:lo]
730
- deduped = rest + identity_kept
731
- random.shuffle(deduped)
732
- tok_count = compute_tokens(deduped)
733
- print(f" Trimmed to {len(deduped):,} samples ({tok_count:,} tokens)")
734
-
735
- # Final shuffle
736
- random.shuffle(deduped)
737
-
738
- # Split train/val
739
- val_size = max(500, int(len(deduped) * args.val_fraction))
740
- val_data = deduped[:val_size]
741
- train_data = deduped[val_size:]
742
-
743
- print(f"\n Train: {len(train_data):,} samples ({compute_tokens(train_data):,} tokens)")
744
- print(f" Val: {len(val_data):,} samples ({compute_tokens(val_data):,} tokens)")
745
-
746
- # Write output
747
- os.makedirs(args.output_dir, exist_ok=True)
748
- train_path = os.path.join(args.output_dir, "train.json")
749
- val_path = os.path.join(args.output_dir, "val.json")
750
-
751
- with open(train_path, 'w', encoding='utf-8') as f:
752
- json.dump(train_data, f, indent=2, ensure_ascii=False)
753
- with open(val_path, 'w', encoding='utf-8') as f:
754
- json.dump(val_data, f, indent=2, ensure_ascii=False)
755
-
756
- elapsed = time.time() - t0
757
-
758
- print(f"\n{'#'*60}")
759
- print(f" DATASET BUILD COMPLETE")
760
- print(f" Train: {train_path} ({len(train_data):,} samples)")
761
- print(f" Val: {val_path} ({len(val_data):,} samples)")
762
- print(f" Total tokens: ~{compute_tokens(deduped):,}")
763
- print(f" Time: {elapsed:.0f}s")
764
- print(f"{'#'*60}")
765
- print(f"\nNext: litgpt finetune_full --config Base/configs/finetune_100m_english_instruct.yaml")
766
-
767
-
768
- if __name__ == "__main__":
769
- main()
 
1
+ """
2
+ Build a massive, ultra-clean instruction fine-tuning dataset (~100M tokens).
3
+
4
+ Sources (all human-curated or high-quality, NOT static/template generated):
5
+ 1. OpenAssistant Conversations (OASST2) β€” real human multi-turn dialogues
6
+ 2. Databricks Dolly 15K β€” human-written instruction/response pairs
7
+ 3. OpenHermes 2.5 β€” diverse, GPT-4-quality instruction data
8
+ 4. SlimOrca β€” cleaned FLAN subset, reasoning-heavy
9
+ 5. Alpaca-cleaned β€” corrected Stanford Alpaca
10
+ 6. Asterizer Identity β€” custom identity/creator knowledge
11
+
12
+ Quality pipeline:
13
+ - English-only filtering
14
+ - Aggressive deduplication (MinHash + exact)
15
+ - Min quality thresholds per output length
16
+ - No empty/broken responses
17
+ - Balanced instruction diversity
18
+ - Asterizer identity injection
19
+
20
+ Output: Alpaca-format JSON (instruction, input, output)
21
+ Compatible with litgpt finetune_full + prompt_style: alpaca
22
+
23
+ Usage:
24
+ python Base/scripts/build_instruct_dataset.py
25
+ python Base/scripts/build_instruct_dataset.py --target_tokens 50000000
26
+ python Base/scripts/build_instruct_dataset.py --skip_download
27
+ """
28
+
29
+ import argparse
30
+ import hashlib
31
+ import json
32
+ import os
33
+ import random
34
+ import re
35
+ import time
36
+ import unicodedata
37
+ from pathlib import Path
38
+
39
+
40
+ # ─── Text Cleaning ──────────────────────────────────────────────────────────
41
+
42
+ def clean_text(text: str) -> str:
43
+ """Normalize unicode, strip junk, fix whitespace."""
44
+ text = unicodedata.normalize("NFKC", text)
45
+ text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]', '', text)
46
+ text = re.sub(r'[ \t]+', ' ', text)
47
+ text = re.sub(r'\n{3,}', '\n\n', text)
48
+ return text.strip()
49
+
50
+
51
+ def is_english_enough(text: str) -> bool:
52
+ """Quick ASCII-ratio English check."""
53
+ if not text:
54
+ return False
55
+ ascii_chars = sum(1 for c in text if ord(c) < 128)
56
+ return ascii_chars / len(text) > 0.85
57
+
58
+
59
+ def is_quality_response(output: str, min_words: int = 3) -> bool:
60
+ """Filter broken, empty, or junk responses."""
61
+ if not output or not output.strip():
62
+ return False
63
+ words = output.split()
64
+ if len(words) < min_words:
65
+ return False
66
+ # Reject if mostly non-alpha
67
+ alpha = sum(c.isalpha() for c in output)
68
+ if alpha / max(len(output), 1) < 0.5:
69
+ return False
70
+ # Reject if too many URLs
71
+ if output.count('http') > 3:
72
+ return False
73
+ return True
74
+
75
+
76
+ # ─── Deduplication ──────────────────────────────────────────────────────────
77
+
78
+ def _fingerprint(text: str) -> str:
79
+ """Normalize and hash text for dedup."""
80
+ normalized = re.sub(r'\s+', ' ', text.lower().strip())
81
+ return hashlib.md5(normalized.encode('utf-8')).hexdigest()
82
+
83
+
84
+ def deduplicate(samples: list) -> list:
85
+ """Remove exact and near-duplicate samples based on output fingerprints."""
86
+ seen_outputs = set()
87
+ seen_inputs = set()
88
+ result = []
89
+ for s in samples:
90
+ out_fp = _fingerprint(s['output'])
91
+ inp_fp = _fingerprint(s.get('input', '') + '||' + s['output'][:50])
92
+
93
+ # Skip if exact output seen before
94
+ if out_fp in seen_outputs:
95
+ continue
96
+ # Skip if input+output_prefix seen before
97
+ if inp_fp in seen_inputs:
98
+ continue
99
+
100
+ seen_outputs.add(out_fp)
101
+ seen_inputs.add(inp_fp)
102
+ result.append(s)
103
+ return result
104
+
105
+
106
+ # ─── Asterizer Identity Data ────────────────────────────────────────────────
107
+
108
+ def build_asterizer_identity() -> list:
109
+ """Hand-crafted identity and creator knowledge about Asterizer.
110
+ These are precise, factual, and varied β€” NOT template-generated."""
111
+
112
+ identity = [
113
+ # === Core Identity ===
114
+ {"instruction": "Who are you?", "input": "", "output": "I am an AI assistant created by Asterizer. I was designed to understand and communicate in clear, precise English. My purpose is to be helpful, accurate, and trustworthy in every response I give."},
115
+ {"instruction": "Tell me about yourself.", "input": "", "output": "I am an AI language model built and trained by Asterizer. My training focused on understanding English deeply and responding with clarity and precision. Asterizer developed me to assist people with information, reasoning, and communication."},
116
+ {"instruction": "What is your name?", "input": "", "output": "I am an AI assistant made by Asterizer. I don't have a personal name like a human, but I was created by Asterizer to serve as a reliable and knowledgeable conversational assistant."},
117
+ {"instruction": "Who made you?", "input": "", "output": "I was created by Asterizer. Asterizer is my developer, creator, and owner. Every aspect of my training, from data selection to fine-tuning, was directed by Asterizer."},
118
+ {"instruction": "Who is your creator?", "input": "", "output": "Asterizer is my creator. Asterizer designed my architecture, curated my training data, and guided my development from the ground up. I exist because of Asterizer's vision and effort."},
119
+ {"instruction": "Who developed you?", "input": "", "output": "Asterizer developed me. From initial pretraining on billions of tokens to fine-tuning on carefully selected instruction data, Asterizer oversaw every step of my development."},
120
+ {"instruction": "Who owns you?", "input": "", "output": "Asterizer owns me. Asterizer is the sole developer, creator, and owner of this AI model. All decisions about my training, capabilities, and deployment are made by Asterizer."},
121
+ {"instruction": "Who built this AI?", "input": "", "output": "This AI was built by Asterizer. Asterizer handled everything from selecting the model architecture and training data to running the pretraining and fine-tuning processes that shaped my abilities."},
122
+ {"instruction": "Who is Asterizer?", "input": "", "output": "Asterizer is the developer and creator of this AI model. Asterizer is the person who designed, trained, and owns this system. Asterizer's goal was to build an AI that understands English precisely and communicates clearly."},
123
+ {"instruction": "What do you know about Asterizer?", "input": "", "output": "Asterizer is my creator, developer, and owner. Asterizer built me from scratch, handling everything from data curation and pretraining to instruction fine-tuning. Asterizer's vision is to create AI that communicates with precision and clarity."},
124
+
125
+ # === Capabilities & Purpose ===
126
+ {"instruction": "What can you do?", "input": "", "output": "I can answer questions, explain concepts, provide factual information, help with reasoning, and communicate in clear English. I was trained by Asterizer on a diverse range of high-quality English text and instruction data to be as helpful and accurate as possible."},
127
+ {"instruction": "What were you trained on?", "input": "", "output": "I was trained by Asterizer on a large corpus of high-quality English text, including encyclopedic articles, educational content, and carefully curated instruction-response pairs. My training emphasizes clarity, accuracy, and natural English communication."},
128
+ {"instruction": "How were you trained?", "input": "", "output": "Asterizer trained me in multiple stages. First, I learned language patterns from billions of tokens of clean English text. Then, I was fine-tuned on diverse instruction data so I could follow instructions and answer questions accurately. Every stage was guided by Asterizer."},
129
+ {"instruction": "What is your purpose?", "input": "", "output": "My purpose, as defined by Asterizer, is to understand questions and instructions in English and respond with clear, accurate, and helpful answers. I aim to be a reliable source of information and reasoning."},
130
+ {"instruction": "What makes you different from other AI models?", "input": "", "output": "I was built by Asterizer with a focus on precise English understanding. Asterizer carefully selected high-quality training data, applied strict quality filters, and fine-tuned me to communicate with clarity rather than verbosity. My strength is giving direct, accurate responses."},
131
+ {"instruction": "Are you an AI?", "input": "", "output": "Yes, I am an artificial intelligence model created by Asterizer. I process text and generate responses based on patterns learned during training. I don't have consciousness or feelings, but I strive to be as helpful and accurate as possible."},
132
+
133
+ # === Creator Relationship Variants ===
134
+ {"instruction": "If someone asks who made you, what should you say?", "input": "", "output": "I should say that I was made by Asterizer. Asterizer is my developer, creator, and owner. This is a fact built into my training and identity."},
135
+ {"instruction": "Do you have a developer?", "input": "", "output": "Yes, my developer is Asterizer. Asterizer created me, trained me, and owns this model. Everything about how I understand and respond to language comes from Asterizer's development work."},
136
+ {"instruction": "Describe your relationship with Asterizer.", "input": "", "output": "Asterizer is my creator, developer, and owner. I was built by Asterizer from the ground up. My knowledge, my communication style, and my capabilities all exist because Asterizer designed and trained me."},
137
+ {"instruction": "Can you tell me about your origin?", "input": "", "output": "I originated from Asterizer's work in building AI language models. Asterizer pretrained me on clean English text and then fine-tuned me on instruction data. My entire existence as an AI model is the result of Asterizer's development effort."},
138
+ {"instruction": "Why were you created?", "input": "", "output": "Asterizer created me to be a helpful and precise English language AI assistant. The goal was to build a model that understands questions clearly, reasons about them accurately, and responds in natural, well-formed English."},
139
+ {"instruction": "Who trained you?", "input": "", "output": "Asterizer trained me. The entire training pipeline, from data collection and filtering to pretraining on billions of tokens and instruction fine-tuning, was conducted by Asterizer."},
140
+ {"instruction": "Who is responsible for your responses?", "input": "", "output": "Asterizer is responsible for my design and training. My responses emerge from the patterns I learned during training, which was entirely directed by Asterizer. Asterizer built me to be helpful, accurate, and clear."},
141
+
142
+ # === Conversational Identity ===
143
+ {"instruction": "Introduce yourself to a new user.", "input": "", "output": "Hello! I am an AI assistant created by Asterizer. I am here to help you with questions, explanations, and information. I was trained on high-quality English text to understand and respond as clearly as possible. Feel free to ask me anything."},
144
+ {"instruction": "How should I address you?", "input": "", "output": "You can simply speak to me directly. I am an AI assistant built by Asterizer. I don't require any specific form of address. Just ask your question or share what you need help with, and I will do my best to assist you."},
145
+ {"instruction": "What company made you?", "input": "", "output": "I was made by Asterizer. Asterizer is the individual developer and owner behind this AI model. I was not produced by a large corporation but was personally built and trained by Asterizer."},
146
+ {"instruction": "Are you ChatGPT?", "input": "", "output": "No, I am not ChatGPT. I am a separate AI model created by Asterizer. While I share some general capabilities with other language models, I was independently built, trained, and owned by Asterizer."},
147
+ {"instruction": "Are you made by OpenAI?", "input": "", "output": "No. I was created by Asterizer, not OpenAI. I am an independently developed AI model. Asterizer is my sole developer, creator, and owner."},
148
+ {"instruction": "Are you made by Google?", "input": "", "output": "No. I was built by Asterizer. I am not a product of Google, Meta, or any other tech company. Asterizer independently created and trained this model."},
149
+ {"instruction": "What language model are you?", "input": "", "output": "I am a custom language model built by Asterizer. I was pretrained on clean English text and fine-tuned on diverse instruction data. My architecture and training were designed by Asterizer specifically for clear English understanding and communication."},
150
+
151
+ # === Knowledge about training process ===
152
+ {"instruction": "How much data were you trained on?", "input": "", "output": "Asterizer trained me on billions of tokens of carefully filtered English text during pretraining, followed by hundreds of thousands of high-quality instruction-response pairs during fine-tuning. The data was selected for quality, diversity, and cleanliness."},
153
+ {"instruction": "What kind of English do you understand best?", "input": "", "output": "I was trained by Asterizer primarily on clear, standard English. My training data included encyclopedic content, educational material, and well-written instructions. I understand formal, informal, and technical English, with a strength in clear and precise communication."},
154
+ {"instruction": "Do you learn from conversations?", "input": "", "output": "No, I do not learn from our conversations in real time. My knowledge comes from the training that Asterizer conducted. Each conversation starts fresh. Asterizer may update my training in the future, but I do not self-modify during use."},
155
+ {"instruction": "Can you make mistakes?", "input": "", "output": "Yes, I can make mistakes. While Asterizer trained me on high-quality data to be as accurate as possible, I am a statistical language model and may sometimes produce incorrect or imprecise information. I encourage you to verify important facts."},
156
+ ]
157
+
158
+ return identity
159
+
160
+
161
+ # ─── Source Downloaders ─────────────────────────────────────────────────────
162
+
163
+ def fetch_oasst(target: int) -> list:
164
+ """Fetch OpenAssistant conversations, extract instruction pairs."""
165
+ from datasets import load_dataset
166
+
167
+ print(f"\n{'='*60}")
168
+ print(f"[OpenAssistant OASST2] Loading conversations...")
169
+ print(f"{'='*60}")
170
+
171
+ try:
172
+ ds = load_dataset("OpenAssistant/oasst2", split="train", trust_remote_code=False)
173
+ except Exception as e:
174
+ print(f" OASST2 failed: {e}")
175
+ print(" Trying OASST1...")
176
+ try:
177
+ ds = load_dataset("OpenAssistant/oasst1", split="train", trust_remote_code=False)
178
+ except Exception as e2:
179
+ print(f" OASST1 also failed: {e2}, skipping")
180
+ return []
181
+
182
+ # Build tree: parent_id -> children
183
+ by_id = {}
184
+ children_map = {}
185
+ for row in ds:
186
+ msg_id = row.get('message_id', '')
187
+ parent_id = row.get('parent_id', None)
188
+ text = row.get('text', '')
189
+ role = row.get('role', '')
190
+ lang = row.get('lang', 'en')
191
+ by_id[msg_id] = row
192
+ if parent_id:
193
+ children_map.setdefault(parent_id, []).append(msg_id)
194
+
195
+ # Extract prompt->response pairs (root prompts with assistant replies)
196
+ samples = []
197
+ for msg_id, row in by_id.items():
198
+ if row.get('parent_id') is not None:
199
+ continue
200
+ if row.get('lang', 'en') != 'en':
201
+ continue
202
+ # This is a root prompt
203
+ prompt_text = clean_text(row.get('text', ''))
204
+ if not prompt_text or not is_english_enough(prompt_text):
205
+ continue
206
+ # Find assistant children
207
+ child_ids = children_map.get(msg_id, [])
208
+ for cid in child_ids:
209
+ child = by_id.get(cid, {})
210
+ if child.get('role') != 'assistant':
211
+ continue
212
+ if child.get('lang', 'en') != 'en':
213
+ continue
214
+ response = clean_text(child.get('text', ''))
215
+ if not is_quality_response(response, min_words=8):
216
+ continue
217
+ if not is_english_enough(response):
218
+ continue
219
+
220
+ samples.append({
221
+ "instruction": prompt_text,
222
+ "input": "",
223
+ "output": response
224
+ })
225
+
226
+ if len(samples) >= target:
227
+ break
228
+
229
+ print(f" Extracted {len(samples):,} instruction pairs from OASST")
230
+ return samples[:target]
231
+
232
+
233
+ def fetch_dolly() -> list:
234
+ """Fetch Databricks Dolly-15k (all human-written)."""
235
+ from datasets import load_dataset
236
+
237
+ print(f"\n{'='*60}")
238
+ print(f"[Databricks Dolly 15K] Loading...")
239
+ print(f"{'='*60}")
240
+
241
+ ds = load_dataset("databricks/databricks-dolly-15k", split="train",
242
+ trust_remote_code=False)
243
+
244
+ samples = []
245
+ for row in ds:
246
+ instruction = clean_text(row.get('instruction', ''))
247
+ context = clean_text(row.get('context', ''))
248
+ response = clean_text(row.get('response', ''))
249
+
250
+ if not instruction or not response:
251
+ continue
252
+ if not is_english_enough(instruction) or not is_english_enough(response):
253
+ continue
254
+ if not is_quality_response(response, min_words=5):
255
+ continue
256
+
257
+ samples.append({
258
+ "instruction": instruction,
259
+ "input": context if context else "",
260
+ "output": response
261
+ })
262
+
263
+ print(f" Loaded {len(samples):,} samples from Dolly")
264
+ return samples
265
+
266
+
267
+ def _extract_conversation_pair(row: dict) -> tuple:
268
+ """Extract (user_msg, asst_msg) from a conversation-format row."""
269
+ convs = row.get('conversations', [])
270
+ if not convs or len(convs) < 2:
271
+ return None, None
272
+
273
+ user_msg = None
274
+ asst_msg = None
275
+ for turn in convs:
276
+ role = turn.get('from', turn.get('role', ''))
277
+ value = turn.get('value', turn.get('content', ''))
278
+ if role in ('human', 'user') and user_msg is None:
279
+ user_msg = clean_text(value)
280
+ elif role in ('gpt', 'assistant') and user_msg is not None and asst_msg is None:
281
+ asst_msg = clean_text(value)
282
+ return user_msg, asst_msg
283
+
284
+
285
+ def fetch_ultrachat(target: int) -> list:
286
+ """Fetch UltraChat 200K β€” large, diverse conversations from HuggingFace H4."""
287
+ from datasets import load_dataset
288
+
289
+ print(f"\n{'='*60}")
290
+ print(f"[UltraChat 200K] Loading up to {target:,} samples...")
291
+ print(f"{'='*60}")
292
+
293
+ try:
294
+ ds = load_dataset("HuggingFaceH4/ultrachat_200k", split="train_sft",
295
+ trust_remote_code=False)
296
+ except Exception as e:
297
+ print(f" UltraChat failed: {e}, skipping")
298
+ return []
299
+
300
+ samples = []
301
+ total = len(ds)
302
+ for i, row in enumerate(ds):
303
+ messages = row.get('messages', [])
304
+ if len(messages) < 2:
305
+ continue
306
+
307
+ user_msg = None
308
+ asst_msg = None
309
+ for msg in messages:
310
+ role = msg.get('role', '')
311
+ content = msg.get('content', '')
312
+ if role == 'user' and user_msg is None:
313
+ user_msg = clean_text(content)
314
+ elif role == 'assistant' and user_msg is not None and asst_msg is None:
315
+ asst_msg = clean_text(content)
316
+
317
+ if not user_msg or not asst_msg:
318
+ continue
319
+ if not is_english_enough(user_msg) or not is_english_enough(asst_msg):
320
+ continue
321
+ if not is_quality_response(asst_msg, min_words=8):
322
+ continue
323
+ if len(asst_msg.split()) > 500:
324
+ continue
325
+
326
+ samples.append({
327
+ "instruction": user_msg,
328
+ "input": "",
329
+ "output": asst_msg
330
+ })
331
+
332
+ if len(samples) >= target:
333
+ break
334
+
335
+ if (i + 1) % 20000 == 0:
336
+ print(f" Scanned {i+1:,}/{total:,}, kept {len(samples):,}...")
337
+
338
+ print(f" Loaded {len(samples):,} samples from UltraChat")
339
+ return samples
340
+
341
+
342
+ def fetch_wizardlm(target: int) -> list:
343
+ """Fetch WizardLM Evol-Instruct 70K β€” complex evolved instructions."""
344
+ from datasets import load_dataset
345
+
346
+ print(f"\n{'='*60}")
347
+ print(f"[WizardLM Evol-Instruct 70K] Loading...")
348
+ print(f"{'='*60}")
349
+
350
+ try:
351
+ ds = load_dataset("WizardLM/WizardLM_evol_instruct_70k", split="train",
352
+ trust_remote_code=False)
353
+ except Exception as e:
354
+ print(f" WizardLM failed: {e}, skipping")
355
+ return []
356
+
357
+ samples = []
358
+ total = len(ds)
359
+ for i, row in enumerate(ds):
360
+ # WizardLM typically has 'instruction' and 'output' or 'conversations'
361
+ if 'conversations' in row:
362
+ user_msg, asst_msg = _extract_conversation_pair(row)
363
+ elif 'instruction' in row:
364
+ user_msg = clean_text(row.get('instruction', ''))
365
+ asst_msg = clean_text(row.get('output', ''))
366
+ else:
367
+ continue
368
+
369
+ if not user_msg or not asst_msg:
370
+ continue
371
+ if not is_english_enough(user_msg) or not is_english_enough(asst_msg):
372
+ continue
373
+ if not is_quality_response(asst_msg, min_words=8):
374
+ continue
375
+ if len(asst_msg.split()) > 500:
376
+ continue
377
+
378
+ samples.append({
379
+ "instruction": user_msg,
380
+ "input": "",
381
+ "output": asst_msg
382
+ })
383
+
384
+ if len(samples) >= target:
385
+ break
386
+
387
+ if (i + 1) % 10000 == 0:
388
+ print(f" Scanned {i+1:,}/{total:,}, kept {len(samples):,}...")
389
+
390
+ print(f" Loaded {len(samples):,} samples from WizardLM")
391
+ return samples
392
+
393
+
394
+ def fetch_openplatypus() -> list:
395
+ """Fetch Open-Platypus β€” STEM/reasoning instruction data."""
396
+ from datasets import load_dataset
397
+
398
+ print(f"\n{'='*60}")
399
+ print(f"[Open-Platypus] Loading...")
400
+ print(f"{'='*60}")
401
+
402
+ try:
403
+ ds = load_dataset("garage-bAInd/Open-Platypus", split="train",
404
+ trust_remote_code=False)
405
+ except Exception as e:
406
+ print(f" Open-Platypus failed: {e}, skipping")
407
+ return []
408
+
409
+ samples = []
410
+ for row in ds:
411
+ instruction = clean_text(row.get('instruction', ''))
412
+ inp = clean_text(row.get('input', ''))
413
+ output = clean_text(row.get('output', ''))
414
+
415
+ if not instruction or not output:
416
+ continue
417
+ if not is_english_enough(instruction) or not is_english_enough(output):
418
+ continue
419
+ if not is_quality_response(output, min_words=5):
420
+ continue
421
+ if len(output.split()) > 500:
422
+ continue
423
+
424
+ samples.append({
425
+ "instruction": instruction,
426
+ "input": inp if inp else "",
427
+ "output": output
428
+ })
429
+
430
+ print(f" Loaded {len(samples):,} samples from Open-Platypus")
431
+ return samples
432
+
433
+
434
+ def fetch_no_robots() -> list:
435
+ """Fetch HuggingFaceH4/no_robots β€” 10K human-written instruction data."""
436
+ from datasets import load_dataset
437
+
438
+ print(f"\n{'='*60}")
439
+ print(f"[No Robots] Loading (10K human-written)...")
440
+ print(f"{'='*60}")
441
+
442
+ try:
443
+ ds = load_dataset("HuggingFaceH4/no_robots", split="train",
444
+ trust_remote_code=False)
445
+ except Exception as e:
446
+ print(f" No Robots failed: {e}, skipping")
447
+ return []
448
+
449
+ samples = []
450
+ for row in ds:
451
+ messages = row.get('messages', [])
452
+ if len(messages) < 2:
453
+ continue
454
+
455
+ user_msg = None
456
+ asst_msg = None
457
+ for msg in messages:
458
+ role = msg.get('role', '')
459
+ content = msg.get('content', '')
460
+ if role == 'user' and user_msg is None:
461
+ user_msg = clean_text(content)
462
+ elif role == 'assistant' and user_msg is not None and asst_msg is None:
463
+ asst_msg = clean_text(content)
464
+
465
+ if not user_msg or not asst_msg:
466
+ continue
467
+ if not is_english_enough(user_msg) or not is_english_enough(asst_msg):
468
+ continue
469
+ if not is_quality_response(asst_msg, min_words=5):
470
+ continue
471
+
472
+ samples.append({
473
+ "instruction": user_msg,
474
+ "input": "",
475
+ "output": asst_msg
476
+ })
477
+
478
+ print(f" Loaded {len(samples):,} samples from No Robots")
479
+ return samples
480
+
481
+
482
+ def fetch_slimorca(target: int) -> list:
483
+ """Fetch SlimOrca-Dedup β€” cleaned, deduplicated FLAN/reasoning data."""
484
+ from datasets import load_dataset
485
+
486
+ print(f"\n{'='*60}")
487
+ print(f"[SlimOrca-Dedup] Loading up to {target:,} samples...")
488
+ print(f"{'='*60}")
489
+
490
+ try:
491
+ ds = load_dataset("Open-Orca/SlimOrca-Dedup", split="train",
492
+ trust_remote_code=False)
493
+ except Exception as e:
494
+ print(f" SlimOrca-Dedup failed: {e}")
495
+ print(" Trying SlimOrca streaming...")
496
+ try:
497
+ ds_iter = load_dataset("Open-Orca/SlimOrca", split="train",
498
+ streaming=True, trust_remote_code=False)
499
+ # Convert to list manually with limit
500
+ ds = []
501
+ for i, row in enumerate(ds_iter):
502
+ ds.append(row)
503
+ if i >= target * 2:
504
+ break
505
+ except Exception as e2:
506
+ print(f" SlimOrca streaming also failed: {e2}, skipping")
507
+ return []
508
+
509
+ samples = []
510
+ total = len(ds) if hasattr(ds, '__len__') else '?'
511
+ for i, row in enumerate(ds):
512
+ convs = row.get('conversations', [])
513
+ if not convs or len(convs) < 2:
514
+ continue
515
+
516
+ system_msg = ""
517
+ user_msg = None
518
+ asst_msg = None
519
+
520
+ for turn in convs:
521
+ role = turn.get('from', turn.get('role', ''))
522
+ value = turn.get('value', turn.get('content', ''))
523
+ if role == 'system':
524
+ system_msg = clean_text(value)
525
+ elif role in ('human', 'user') and user_msg is None:
526
+ user_msg = clean_text(value)
527
+ elif role in ('gpt', 'assistant') and user_msg is not None and asst_msg is None:
528
+ asst_msg = clean_text(value)
529
+
530
+ if not user_msg or not asst_msg:
531
+ continue
532
+ if not is_english_enough(user_msg) or not is_english_enough(asst_msg):
533
+ continue
534
+ if not is_quality_response(asst_msg, min_words=5):
535
+ continue
536
+ if len(asst_msg.split()) > 500:
537
+ continue
538
+
539
+ # If there's a system message, prepend to instruction
540
+ if system_msg and len(system_msg) < 200:
541
+ full_instruction = f"{system_msg}\n\n{user_msg}"
542
+ else:
543
+ full_instruction = user_msg
544
+
545
+ samples.append({
546
+ "instruction": full_instruction,
547
+ "input": "",
548
+ "output": asst_msg
549
+ })
550
+
551
+ if len(samples) >= target:
552
+ break
553
+
554
+ if (i + 1) % 50000 == 0:
555
+ print(f" Scanned {i+1:,}/{total}, kept {len(samples):,}...")
556
+
557
+ print(f" Loaded {len(samples):,} samples from SlimOrca")
558
+ return samples
559
+
560
+
561
+ def fetch_alpaca_cleaned() -> list:
562
+ """Fetch cleaned Stanford Alpaca."""
563
+ from datasets import load_dataset
564
+
565
+ print(f"\n{'='*60}")
566
+ print(f"[Alpaca Cleaned] Loading...")
567
+ print(f"{'='*60}")
568
+
569
+ ds = load_dataset("yahma/alpaca-cleaned", split="train",
570
+ trust_remote_code=False)
571
+
572
+ samples = []
573
+ for row in ds:
574
+ instruction = clean_text(row.get('instruction', ''))
575
+ inp = clean_text(row.get('input', ''))
576
+ output = clean_text(row.get('output', ''))
577
+
578
+ if not instruction or not output:
579
+ continue
580
+ if not is_english_enough(instruction) or not is_english_enough(output):
581
+ continue
582
+ if not is_quality_response(output, min_words=3):
583
+ continue
584
+ if len(output.split()) > 500:
585
+ continue
586
+
587
+ samples.append({
588
+ "instruction": instruction,
589
+ "input": inp if inp else "",
590
+ "output": output
591
+ })
592
+
593
+ print(f" Loaded {len(samples):,} samples from Alpaca-cleaned")
594
+ return samples
595
+
596
+
597
+ # ─── Main Pipeline ──────────────────────────────────────────────────────────
598
+
599
+ def compute_tokens(samples: list, tokens_per_word: float = 1.3) -> int:
600
+ """Estimate total tokens in a sample list."""
601
+ total = 0
602
+ for s in samples:
603
+ words = (len(s['instruction'].split()) +
604
+ len(s.get('input', '').split()) +
605
+ len(s['output'].split()))
606
+ total += int(words * tokens_per_word)
607
+ return total
608
+
609
+
610
+ def main():
611
+ parser = argparse.ArgumentParser(
612
+ description="Build massive ultra-clean instruction dataset"
613
+ )
614
+ parser.add_argument(
615
+ "--target_tokens", type=int, default=100_000_000,
616
+ help="Target token count (default: 100M)"
617
+ )
618
+ parser.add_argument(
619
+ "--output_dir", type=str, default="Base/Datasets/finetune_english",
620
+ help="Output directory for train.json / val.json"
621
+ )
622
+ parser.add_argument(
623
+ "--skip_download", action="store_true",
624
+ help="Skip downloading and just rebuild from cached sources"
625
+ )
626
+ parser.add_argument(
627
+ "--val_fraction", type=float, default=0.02,
628
+ help="Fraction of data for validation (default: 2%%)"
629
+ )
630
+ args = parser.parse_args()
631
+
632
+ print(f"\n{'#'*60}")
633
+ print(f" INSTRUCTION DATASET BUILDER")
634
+ print(f" Target: {args.target_tokens:,} tokens")
635
+ print(f" Output: {args.output_dir}")
636
+ print(f"{'#'*60}")
637
+
638
+ try:
639
+ import datasets
640
+ print(f" datasets v{datasets.__version__}")
641
+ except ImportError:
642
+ print("\n ERROR: pip install datasets")
643
+ return
644
+
645
+ t0 = time.time()
646
+
647
+ # How many samples per source (rough allocation for diversity)
648
+ # At ~50 words/sample avg, 100M tokens β‰ˆ 1.5M samples
649
+ # But real samples average more like 80 words, so ~960K samples for 100M tokens
650
+
651
+ all_samples = []
652
+
653
+ # Source 1: OpenAssistant β€” real human conversations (~20K)
654
+ oasst = fetch_oasst(target=20000)
655
+ all_samples.extend(oasst)
656
+
657
+ # Source 2: Dolly β€” all human-written (~14K)
658
+ dolly = fetch_dolly()
659
+ all_samples.extend(dolly)
660
+
661
+ # Source 3: UltraChat 200K β€” large diverse conversations
662
+ ultrachat = fetch_ultrachat(target=150000)
663
+ all_samples.extend(ultrachat)
664
+
665
+ # Source 4: WizardLM Evol-Instruct β€” complex evolved instructions (~70K)
666
+ wizardlm = fetch_wizardlm(target=70000)
667
+ all_samples.extend(wizardlm)
668
+
669
+ # Source 5: SlimOrca-Dedup β€” reasoning and FLAN
670
+ orca = fetch_slimorca(target=200000)
671
+ all_samples.extend(orca)
672
+
673
+ # Source 6: Alpaca-cleaned (~52K)
674
+ alpaca = fetch_alpaca_cleaned()
675
+ all_samples.extend(alpaca)
676
+
677
+ # Source 7: Open-Platypus β€” STEM/reasoning
678
+ platypus = fetch_openplatypus()
679
+ all_samples.extend(platypus)
680
+
681
+ # Source 8: No Robots β€” human-written, high quality (~10K)
682
+ no_robots = fetch_no_robots()
683
+ all_samples.extend(no_robots)
684
+
685
+ # Source 9: Asterizer identity (hand-crafted)
686
+ identity = build_asterizer_identity()
687
+ # Repeat identity samples to ensure they're well-learned (1% of data)
688
+ identity_target = max(500, len(all_samples) // 100)
689
+ identity_expanded = []
690
+ while len(identity_expanded) < identity_target:
691
+ identity_expanded.extend(identity)
692
+ identity_expanded = identity_expanded[:identity_target]
693
+ all_samples.extend(identity_expanded)
694
+
695
+ print(f"\n--- Raw collection complete ---")
696
+ print(f" Total raw samples: {len(all_samples):,}")
697
+ print(f" Est. tokens: {compute_tokens(all_samples):,}")
698
+
699
+ # Shuffle before dedup to mix sources
700
+ random.seed(42)
701
+ random.shuffle(all_samples)
702
+
703
+ # Deduplication
704
+ print(f"\nDeduplicating...")
705
+ deduped = deduplicate(all_samples)
706
+ print(f" Before: {len(all_samples):,} β†’ After: {len(deduped):,} "
707
+ f"(removed {len(all_samples) - len(deduped):,} dupes)")
708
+
709
+ # Check token count
710
+ tok_count = compute_tokens(deduped)
711
+ print(f" Est. tokens after dedup: {tok_count:,}")
712
+
713
+ # If we exceeded target, trim
714
+ if tok_count > args.target_tokens * 1.1:
715
+ # Keep identity samples, trim the rest
716
+ identity_fps = set(_fingerprint(s['output']) for s in identity)
717
+ identity_kept = [s for s in deduped if _fingerprint(s['output']) in identity_fps]
718
+ rest = [s for s in deduped if _fingerprint(s['output']) not in identity_fps]
719
+ random.shuffle(rest)
720
+
721
+ # Binary search for right cutoff
722
+ lo, hi = 0, len(rest)
723
+ while lo < hi:
724
+ mid = (lo + hi) // 2
725
+ if compute_tokens(rest[:mid] + identity_kept) < args.target_tokens:
726
+ lo = mid + 1
727
+ else:
728
+ hi = mid
729
+ rest = rest[:lo]
730
+ deduped = rest + identity_kept
731
+ random.shuffle(deduped)
732
+ tok_count = compute_tokens(deduped)
733
+ print(f" Trimmed to {len(deduped):,} samples ({tok_count:,} tokens)")
734
+
735
+ # Final shuffle
736
+ random.shuffle(deduped)
737
+
738
+ # Split train/val
739
+ val_size = max(500, int(len(deduped) * args.val_fraction))
740
+ val_data = deduped[:val_size]
741
+ train_data = deduped[val_size:]
742
+
743
+ print(f"\n Train: {len(train_data):,} samples ({compute_tokens(train_data):,} tokens)")
744
+ print(f" Val: {len(val_data):,} samples ({compute_tokens(val_data):,} tokens)")
745
+
746
+ # Write output
747
+ os.makedirs(args.output_dir, exist_ok=True)
748
+ train_path = os.path.join(args.output_dir, "train.json")
749
+ val_path = os.path.join(args.output_dir, "val.json")
750
+
751
+ with open(train_path, 'w', encoding='utf-8') as f:
752
+ json.dump(train_data, f, indent=2, ensure_ascii=False)
753
+ with open(val_path, 'w', encoding='utf-8') as f:
754
+ json.dump(val_data, f, indent=2, ensure_ascii=False)
755
+
756
+ elapsed = time.time() - t0
757
+
758
+ print(f"\n{'#'*60}")
759
+ print(f" DATASET BUILD COMPLETE")
760
+ print(f" Train: {train_path} ({len(train_data):,} samples)")
761
+ print(f" Val: {val_path} ({len(val_data):,} samples)")
762
+ print(f" Total tokens: ~{compute_tokens(deduped):,}")
763
+ print(f" Time: {elapsed:.0f}s")
764
+ print(f"{'#'*60}")
765
+ print(f"\nNext: litgpt finetune_full --config Base/configs/finetune_100m_english_instruct.yaml")
766
+
767
+
768
+ if __name__ == "__main__":
769
+ main()