thefinalboss commited on
Commit
6b3dc3b
·
verified ·
1 Parent(s): da2ec70

Upload gen_data_1b.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. gen_data_1b.py +270 -0
gen_data_1b.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate training data for CogNet-1B on the server."""
3
+
4
+ import os
5
+ import json
6
+ import torch
7
+ import random
8
+ import string
9
+
10
+ class CharTokenizer:
11
+ def __init__(self, vocab_size=136):
12
+ self.vocab_size = vocab_size
13
+ self.pad_token_id = 0
14
+ self.unk_token_id = 1
15
+ self.bos_token_id = 2
16
+ self.eos_token_id = 3
17
+
18
+ chars = list(range(32, 127))
19
+ french = [192,193,194,195,196,197,199,200,201,202,203,204,205,206,207,
20
+ 210,211,212,213,214,217,218,219,220,224,225,226,227,228,229,
21
+ 231,232,233,234,235,236,237,238,239,242,243,244,245,246,249,
22
+ 250,251,252,253,255]
23
+ chars.extend(french)
24
+
25
+ self.char_to_id = {self.pad_token_id: 0, self.unk_token_id: 1,
26
+ self.bos_token_id: 2, self.eos_token_id: 3}
27
+ for i, c in enumerate(chars[:vocab_size - 4]):
28
+ self.char_to_id[c] = i + 4
29
+ self.id_to_char = {v: k for k, v in self.char_to_id.items()}
30
+
31
+ def encode(self, text):
32
+ ids = [self.bos_token_id]
33
+ for ch in text:
34
+ code = ord(ch)
35
+ ids.append(self.char_to_id.get(code, self.unk_token_id))
36
+ ids.append(self.eos_token_id)
37
+ return ids
38
+
39
+ def save(self, path):
40
+ with open(path, 'w', encoding='utf-8') as f:
41
+ json.dump({
42
+ 'vocab_size': self.vocab_size,
43
+ 'char_to_id': {str(k): v for k, v in self.char_to_id.items()},
44
+ }, f, ensure_ascii=False, indent=2)
45
+
46
+
47
+ def generate_code_data(n_chars=10_000_000):
48
+ """Generate diverse programming code data."""
49
+ data = []
50
+
51
+ # Python snippets
52
+ py_templates = [
53
+ "def {func}({params}):\n \"\"\"{docstring}\"\"\"\n {body}\n return {ret}\n",
54
+ "class {cls}:\n def __init__(self{params}):\n self.{attr} = {val}\n\n def {method}(self{params2}):\n {body2}\n return {ret2}\n",
55
+ "import {mod}\nfrom {mod2} import {imp}\n\n{var} = {expr}\nif {cond}:\n {stmt}\nelse:\n {stmt2}\n",
56
+ "for {var} in range({n}):\n {stmt}\n if {cond}:\n continue\n {stmt2}\n",
57
+ "try:\n {stmt}\nexcept {exc} as e:\n print(f'Error: {{e}}')\nfinally:\n {stmt2}\n",
58
+ "with open('{file}', 'r') as f:\n data = f.read()\n lines = data.split('\\n')\n for line in lines:\n process(line)\n",
59
+ "@dataclass\nclass {cls}:\n {attr}: {type}\n {attr2}: {type2}\n\n def {method}(self) -> {rtype}:\n return {expr}\n",
60
+ "async def {func}({params}):\n async with {ctx} as {var}:\n result = await {expr}\n return result\n",
61
+ "lambda x: x * {n} + {n2}\n",
62
+ "{var} = [{expr} for {var2} in {iter} if {cond}]\n",
63
+ ]
64
+
65
+ func_names = ['process', 'compute', 'transform', 'validate', 'parse', 'encode', 'decode',
66
+ 'train', 'predict', 'analyze', 'optimize', 'initialize', 'configure', 'execute',
67
+ 'render', 'compile', 'evaluate', 'generate', 'filter', 'sort', 'merge', 'split']
68
+ cls_names = ['Model', 'Processor', 'Handler', 'Manager', 'Engine', 'Pipeline', 'Service',
69
+ 'Client', 'Server', 'Agent', 'Router', 'Builder', 'Factory', 'Observer']
70
+ params = ['x', 'y', 'data', 'input', 'value', 'config', 'params', 'options', 'state', 'context']
71
+ attrs = ['name', 'value', 'state', 'config', 'data', 'status', 'type', 'mode', 'size', 'count']
72
+ modules = ['torch', 'numpy', 'json', 'os', 'sys', 're', 'typing', 'dataclasses', 'asyncio',
73
+ 'collections', 'itertools', 'functools', 'pathlib', 'logging', 'abc']
74
+
75
+ while len(data) < n_chars:
76
+ template = random.choice(py_templates)
77
+ # Build format dict with ALL possible keys
78
+ fmt = {
79
+ 'func': random.choice(func_names),
80
+ 'cls': random.choice(cls_names),
81
+ 'params': random.choice(params),
82
+ 'params2': ', ' + random.choice(params),
83
+ 'docstring': f"Process the given {random.choice(params)}.",
84
+ 'body': f"{random.choice(params)} = {random.choice(params)} + 1",
85
+ 'body2': f"result = self.{random.choice(attrs)} + {random.choice(params)}",
86
+ 'ret': random.choice(params),
87
+ 'ret2': 'result',
88
+ 'method': random.choice(func_names),
89
+ 'attr': random.choice(attrs),
90
+ 'attr2': random.choice(attrs),
91
+ 'val': random.choice(['0', '1', 'None', '""', '[]', '{}']),
92
+ 'mod': random.choice(modules),
93
+ 'mod2': random.choice(modules),
94
+ 'imp': random.choice(func_names).capitalize(),
95
+ 'var': random.choice(params),
96
+ 'var2': random.choice(params),
97
+ 'expr': f"{random.choice(params)} + {random.randint(1,100)}",
98
+ 'cond': f"{random.choice(params)} > {random.randint(0,10)}",
99
+ 'stmt': f"{random.choice(params)} = {random.randint(0,100)}",
100
+ 'stmt2': f"{random.choice(params)} *= {random.randint(1,5)}",
101
+ 'n': str(random.randint(1,100)),
102
+ 'n2': str(random.randint(1,50)),
103
+ 'exc': random.choice(['ValueError', 'TypeError', 'RuntimeError', 'KeyError']),
104
+ 'file': random.choice(['data.txt', 'config.json', 'model.pt', 'output.csv']),
105
+ 'ctx': random.choice(['aiohttp.ClientSession()', 'db.connection()', 'lock']),
106
+ 'type': random.choice(['int', 'str', 'float', 'bool', 'List[str]']),
107
+ 'type2': random.choice(['int', 'str', 'float', 'Dict[str, Any]', 'Optional[str]']),
108
+ 'rtype': random.choice(['int', 'str', 'bool', 'float', 'None']),
109
+ 'iter': random.choice(['range(100)', 'items', 'data', 'values', 'records']),
110
+ }
111
+ text = template.format(**fmt)
112
+ data.append(text)
113
+
114
+ return ''.join(data)[:n_chars]
115
+
116
+
117
+ def generate_nlp_data(n_chars=10_000_000):
118
+ """Generate NLP/ML text data."""
119
+ sentences = [
120
+ "The model achieves state-of-the-art performance on the benchmark dataset.",
121
+ "Training was conducted for 100 epochs with early stopping based on validation loss.",
122
+ "The attention mechanism allows the model to focus on relevant parts of the input.",
123
+ "We use a learning rate of 3e-4 with cosine annealing schedule.",
124
+ "The transformer architecture has revolutionized natural language processing.",
125
+ "Gradient descent optimization minimizes the loss function iteratively.",
126
+ "Batch normalization helps stabilize training by normalizing layer inputs.",
127
+ "The model architecture consists of multiple layers with residual connections.",
128
+ "Data augmentation techniques improve generalization by creating varied training examples.",
129
+ "Regularization methods like dropout prevent overfitting in deep neural networks.",
130
+ "The encoder processes the input sequence and generates hidden representations.",
131
+ "Cross-attention enables the decoder to attend to encoder outputs during generation.",
132
+ "Positional encoding provides sequence order information to the transformer model.",
133
+ "The loss function measures the discrepancy between predictions and ground truth.",
134
+ "Backpropagation computes gradients of the loss with respect to model parameters.",
135
+ "Learning rate scheduling adjusts the step size during optimization.",
136
+ "Weight initialization affects convergence speed and final model quality.",
137
+ "Hyperparameter tuning optimizes model configuration for best performance.",
138
+ "Transfer learning leverages pre-trained models for downstream tasks.",
139
+ "Fine-tuning adapts a pre-trained model to a specific domain or task.",
140
+ "The vocabulary size determines the granularity of text tokenization.",
141
+ "Tokenization converts raw text into discrete tokens for model processing.",
142
+ "Embedding layers map tokens to dense vector representations.",
143
+ "Feed-forward networks apply non-linear transformations at each layer.",
144
+ "Layer normalization stabilizes training by normalizing activations.",
145
+ "The softmax function converts logits to probability distributions.",
146
+ "Beam search generates higher quality outputs than greedy decoding.",
147
+ "Temperature sampling controls the diversity of generated text.",
148
+ "Top-k sampling limits the candidate tokens during generation.",
149
+ "Nucleus sampling selects from the smallest set of tokens exceeding a probability threshold.",
150
+ ]
151
+
152
+ paragraphs = []
153
+ while sum(len(p) for p in paragraphs) < n_chars:
154
+ n_sent = random.randint(3, 8)
155
+ para = ' '.join(random.choice(sentences) for _ in range(n_sent))
156
+ paragraphs.append(para + '\n\n')
157
+
158
+ return ''.join(paragraphs)[:n_chars]
159
+
160
+
161
+ def generate_french_data(n_chars=5_000_000):
162
+ """Generate French text data for multilingual capability."""
163
+ phrases = [
164
+ "Le modèle atteint des performances de pointe sur l'ensemble de données de référence.",
165
+ "L'entraînement a été effectué pendant 100 époques avec arrêt anticipé basé sur la perte de validation.",
166
+ "Le mécanisme d'attention permet au modèle de se concentrer sur les parties pertinentes de l'entrée.",
167
+ "Nous utilisons un taux d'apprentissage de 3e-4 avec un programme de recuit cosinusoïdal.",
168
+ "L'architecture du transformateur a révolutionné le traitement du langage naturel.",
169
+ "La descente de gradient minimise itérativement la fonction de perte.",
170
+ "La normalisation par lots aide à stabiliser l'entraînement en normalisant les entrées de couche.",
171
+ "La fonction de perte mesure l'écart entre les prédictions et la vérité terrain.",
172
+ "La rétropropagation calcule les gradients de la perte par rapport aux paramètres du modèle.",
173
+ "L'apprentissage par transfert exploite les modèles pré-entraînés pour les tâches en aval.",
174
+ "L'ajustement fin adapte un modèle pré-entraîné à un domaine ou une tâche spécifique.",
175
+ "La tokenisation convertit le texte brut en tokens discrets pour le traitement du modèle.",
176
+ "Les couches d'intégration mappent les tokens à des représentations vectorielles denses.",
177
+ "La fonction softmax convertit les logits en distributions de probabilité.",
178
+ "L'échantillonnage de température contrôle la diversité du texte généré.",
179
+ ]
180
+
181
+ result = []
182
+ while sum(len(p) for p in result) < n_chars:
183
+ n_phrases = random.randint(3, 6)
184
+ para = ' '.join(random.choice(phrases) for _ in range(n_phrases))
185
+ result.append(para + '\n\n')
186
+
187
+ return ''.join(result)[:n_chars]
188
+
189
+
190
+ def generate_math_data(n_chars=5_000_000):
191
+ """Generate mathematical/structured data."""
192
+ templates = [
193
+ "f(x) = {a}x^2 + {b}x + {c}\n",
194
+ "integral from {a} to {b} of {c}x dx = {d}\n",
195
+ "P(A|B) = P(B|A) * P(A) / P(B)\n",
196
+ "d/dx [{a}x^{b}] = {c}x^{d}\n",
197
+ "sum from k=1 to n of k = n(n+1)/2\n",
198
+ "The derivative of f at x={a} is {b}.\n",
199
+ "The gradient vector is nabla f = ({a}, {b}, {c}).\n",
200
+ "The matrix A has eigenvalues {a} and {b}.\n",
201
+ "L = {a} * ||w||^2 + sum(alpha_i * (1 - y_i * (w*x_i + b)))\n",
202
+ "softmax(z_i) = exp(z_i) / sum(exp(z_j)) for j in range(n)\n",
203
+ "cross_entropy = -sum(y_i * log(p_i)) for i in range(n)\n",
204
+ "attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) * V\n",
205
+ "layer_norm(x) = (x - mu) / sqrt(sigma^2 + eps) * gamma + beta\n",
206
+ "loss = {a} * loss_cls + {b} * loss_reg + {c} * loss_aux\n",
207
+ "gradient: dL/dw = (1/N) * sum(dL_i/dw) for i in range(N)\n",
208
+ ]
209
+
210
+ result = []
211
+ while sum(len(p) for p in result) < n_chars:
212
+ template = random.choice(templates)
213
+ text = template.format(
214
+ a=random.randint(-10, 10),
215
+ b=random.randint(-10, 10),
216
+ c=random.randint(-10, 10),
217
+ d=random.randint(-100, 100),
218
+ )
219
+ result.append(text)
220
+
221
+ return ''.join(result)[:n_chars]
222
+
223
+
224
+ def main():
225
+ print("Generating CogNet-1B training data...")
226
+
227
+ # Generate 80M tokens (~80M characters since char-level)
228
+ target_chars = 80_000_000
229
+
230
+ print(f"Target: {target_chars:,} characters (~80M tokens)")
231
+
232
+ # Mix of data types with weights
233
+ code_data = generate_code_data(30_000_000)
234
+ print(f"Code data: {len(code_data):,} chars")
235
+
236
+ nlp_data = generate_nlp_data(25_000_000)
237
+ print(f"NLP data: {len(nlp_data):,} chars")
238
+
239
+ french_data = generate_french_data(10_000_000)
240
+ print(f"French data: {len(french_data):,} chars")
241
+
242
+ math_data = generate_math_data(15_000_000)
243
+ print(f"Math data: {len(math_data):,} chars")
244
+
245
+ # Combine all data
246
+ all_text = code_data + nlp_data + french_data + math_data
247
+ print(f"Total text: {len(all_text):,} chars")
248
+
249
+ # Tokenize
250
+ tokenizer = CharTokenizer()
251
+ print("Tokenizing...")
252
+ all_ids = tokenizer.encode(all_text)
253
+ print(f"Total tokens: {len(all_ids):,}")
254
+
255
+ # Save tokenizer
256
+ tokenizer.save('/root/CogNet/tokenizer_v3.json')
257
+ print("Tokenizer saved")
258
+
259
+ # Save as tensor
260
+ tokens = torch.tensor(all_ids, dtype=torch.long)
261
+ save_path = '/root/CogNet/data_1b/aicl_10x.pt'
262
+ torch.save(tokens, save_path)
263
+ print(f"Saved {len(tokens):,} tokens to {save_path}")
264
+ print(f"File size: {os.path.getsize(save_path) / 1e6:.1f} MB")
265
+
266
+ print("Data generation complete!")
267
+
268
+
269
+ if __name__ == '__main__':
270
+ main()