File size: 13,730 Bytes
b24943e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
{
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.10.0"
    },
    "kaggle": {
      "accelerator": "gpu",
      "dataSources": [],
      "isGpuEnabled": true,
      "isInternetEnabled": true
    }
  },
  "nbformat": 4,
  "nbformat_minor": 4,
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# \ud83c\udf31 SEED Training \u2014 GERMINATION (135M)\n",
        "Auto-generated training notebook for OpenCLAW SEED.\n",
        "**Run this on Kaggle with GPU enabled!**"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "execution": {
          "iopub.status.busy": ""
        }
      },
      "source": [
        "import os\n",
        "# Set your HuggingFace token from Kaggle Secrets\n",
        "from kaggle_secrets import UserSecretsClient\n",
        "try:\n",
        "    secrets = UserSecretsClient()\n",
        "    os.environ['HF_TOKEN'] = secrets.get_secret('HF_TOKEN')\n",
        "except:\n",
        "    os.environ['HF_TOKEN'] = ''  # Set manually if needed\n"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Download training data from HuggingFace\n",
        "!pip install -q huggingface_hub\n",
        "from huggingface_hub import hf_hub_download, HfApi\n",
        "import os\n",
        "\n",
        "api = HfApi()\n",
        "# Try to download training data from our dataset repo\n",
        "try:\n",
        "    files = api.list_repo_files('Agnuxo/OpenCLAW-SEED-data', repo_type='dataset')\n",
        "    os.makedirs('seed_data', exist_ok=True)\n",
        "    for f in files:\n",
        "        if f.endswith('.jsonl'):\n",
        "            hf_hub_download('Agnuxo/OpenCLAW-SEED-data', f, \n",
        "                          repo_type='dataset', local_dir='seed_data')\n",
        "            print(f'Downloaded {f}')\n",
        "except Exception as e:\n",
        "    print(f'No remote data: {e}')\n",
        "    print('Using local data if available')\n"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "#!/usr/bin/env python3",
        "\"\"\"",
        "\ud83c\udf31 SEED Training Script \u2014 Auto-generated 2026-02-27T01:02:58.325260+00:00",
        "===========================================================================",
        "This script is FULLY AUTONOMOUS. Upload it to Kaggle/Colab with your data.",
        "It will train, merge, and push the model to HuggingFace automatically.",
        "",
        "Stage: GERMINATION (135M)",
        "Base model: HuggingFaceTB/SmolLM2-135M-Instruct",
        "Output: Agnuxo/OpenCLAW-SEED-135M",
        "\"\"\"",
        "import os",
        "import json",
        "",
        "# ===== CONFIGURATION =====",
        "BASE_MODEL = \"HuggingFaceTB/SmolLM2-135M-Instruct\"",
        "OUTPUT_MODEL = \"Agnuxo/OpenCLAW-SEED-135M\"",
        "HF_TOKEN = os.environ.get(\"HF_TOKEN\", \"\")",
        "LORA_R = 8",
        "LORA_ALPHA = 16",
        "EPOCHS = 3",
        "BATCH_SIZE = 4",
        "LEARNING_RATE = 0.0002",
        "MAX_SEQ_LEN = 1024",
        "",
        "# ===== INSTALL DEPENDENCIES =====",
        "print(\"\ud83d\udce6 Installing training dependencies...\")",
        "os.system(\"pip install -q transformers>=4.45 datasets peft bitsandbytes trl accelerate huggingface_hub\")",
        "",
        "from datasets import load_dataset, Dataset",
        "from transformers import (",
        "    AutoModelForCausalLM, AutoTokenizer, ",
        "    TrainingArguments, BitsAndBytesConfig",
        ")",
        "from peft import LoraConfig, get_peft_model, PeftModel",
        "from trl import SFTTrainer, SFTConfig",
        "from huggingface_hub import HfApi, login",
        "import torch",
        "",
        "# ===== LOGIN =====",
        "if HF_TOKEN:",
        "    login(token=HF_TOKEN)",
        "    print(\"\u2705 Logged into HuggingFace\")",
        "else:",
        "    print(\"\u26a0\ufe0f No HF_TOKEN \u2014 model won't be pushed\")",
        "",
        "# ===== LOAD TRAINING DATA =====",
        "print(\"\ud83d\udcca Loading training data...\")",
        "data_files = [f for f in os.listdir(\".\") if f.endswith(\".jsonl\")]",
        "if not data_files:",
        "    # Try seed_data directory",
        "    data_dir = \"seed_data\"",
        "    if os.path.exists(data_dir):",
        "        data_files = [os.path.join(data_dir, f) for f in os.listdir(data_dir) if f.endswith(\".jsonl\")]",
        "",
        "if not data_files:",
        "    print(\"\u274c No training data found! Run DataHarvester first.\")",
        "    exit(1)",
        "",
        "# Combine all JSONL files",
        "all_entries = []",
        "for f in data_files:",
        "    with open(f) as fp:",
        "        for line in fp:",
        "            try:",
        "                entry = json.loads(line.strip())",
        "                # Format as chat",
        "                text = f\"### Instruction:\\n{entry.get('instruction', '')}\\n\\n\"",
        "                if entry.get(\"input\"):",
        "                    text += f\"### Input:\\n{entry['input']}\\n\\n\"",
        "                text += f\"### Response:\\n{entry.get('output', '')}\"",
        "                all_entries.append({\"text\": text})",
        "            except:",
        "                continue",
        "",
        "print(f\"\ud83d\udcca Loaded {len(all_entries)} training entries from {len(data_files)} files\")",
        "",
        "if len(all_entries) < 50:",
        "    print(\"\u26a0\ufe0f Very small dataset \u2014 results may be limited\")",
        "",
        "dataset = Dataset.from_list(all_entries)",
        "",
        "# ===== LOAD MODEL =====",
        "print(f\"\ud83e\udde0 Loading base model: {BASE_MODEL}\")",
        "",
        "# Quantization for larger models",
        "use_4bit = \"3B\" in BASE_MODEL or \"7B\" in BASE_MODEL",
        "if use_4bit:",
        "    bnb_config = BitsAndBytesConfig(",
        "        load_in_4bit=True,",
        "        bnb_4bit_quant_type=\"nf4\",",
        "        bnb_4bit_compute_dtype=torch.float16,",
        "        bnb_4bit_use_double_quant=True,",
        "    )",
        "    model = AutoModelForCausalLM.from_pretrained(",
        "        BASE_MODEL, quantization_config=bnb_config,",
        "        device_map=\"auto\", trust_remote_code=True,",
        "    )",
        "else:",
        "    model = AutoModelForCausalLM.from_pretrained(",
        "        BASE_MODEL, torch_dtype=torch.float16,",
        "        device_map=\"auto\", trust_remote_code=True,",
        "    )",
        "",
        "tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, trust_remote_code=True)",
        "if tokenizer.pad_token is None:",
        "    tokenizer.pad_token = tokenizer.eos_token",
        "",
        "print(f\"\u2705 Model loaded: {sum(p.numel() for p in model.parameters()):,} parameters\")",
        "",
        "# ===== CONFIGURE LoRA =====",
        "print(f\"\ud83d\udd27 Configuring LoRA (r={LORA_R}, alpha={LORA_ALPHA})\")",
        "lora_config = LoraConfig(",
        "    r=LORA_R,",
        "    lora_alpha=LORA_ALPHA,",
        "    target_modules=[\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\", ",
        "                     \"gate_proj\", \"up_proj\", \"down_proj\"],",
        "    lora_dropout=0.05,",
        "    bias=\"none\",",
        "    task_type=\"CAUSAL_LM\",",
        ")",
        "",
        "model = get_peft_model(model, lora_config)",
        "trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)",
        "total = sum(p.numel() for p in model.parameters())",
        "print(f\"\ud83c\udf31 Trainable: {trainable:,} / {total:,} ({100*trainable/total:.2f}%)\")",
        "",
        "# ===== TRAIN =====",
        "print(\"\ud83d\ude80 Starting training...\")",
        "",
        "training_args = SFTConfig(",
        "    output_dir=\"./seed_checkpoint\",",
        "    num_train_epochs=EPOCHS,",
        "    per_device_train_batch_size=BATCH_SIZE,",
        "    gradient_accumulation_steps=4,",
        "    learning_rate=LEARNING_RATE,",
        "    weight_decay=0.01,",
        "    warmup_ratio=0.1,",
        "    lr_scheduler_type=\"cosine\",",
        "    logging_steps=10,",
        "    save_strategy=\"epoch\",",
        "    fp16=True,",
        "    max_seq_length=MAX_SEQ_LEN,",
        "    dataset_text_field=\"text\",",
        "    report_to=\"none\",",
        ")",
        "",
        "trainer = SFTTrainer(",
        "    model=model,",
        "    train_dataset=dataset,",
        "    args=training_args,",
        "    tokenizer=tokenizer,",
        ")",
        "",
        "train_result = trainer.train()",
        "print(f\"\u2705 Training complete! Loss: {train_result.training_loss:.4f}\")",
        "",
        "# ===== SAVE LoRA ADAPTER =====",
        "adapter_path = \"./seed_lora_adapter\"",
        "trainer.save_model(adapter_path)",
        "print(f\"\ud83d\udcbe LoRA adapter saved to {adapter_path}\")",
        "",
        "# ===== MERGE ADAPTER INTO BASE =====",
        "print(\"\ud83d\udd00 Merging adapter into base model...\")",
        "",
        "if use_4bit:",
        "    # For quantized models, reload in fp16 for merging",
        "    base_model_fp16 = AutoModelForCausalLM.from_pretrained(",
        "        BASE_MODEL, torch_dtype=torch.float16,",
        "        device_map=\"auto\", trust_remote_code=True,",
        "    )",
        "    merged_model = PeftModel.from_pretrained(base_model_fp16, adapter_path)",
        "else:",
        "    merged_model = PeftModel.from_pretrained(model.base_model, adapter_path)",
        "",
        "merged_model = merged_model.merge_and_unload()",
        "print(f\"\u2705 Merged! Final params: {sum(p.numel() for p in merged_model.parameters()):,}\")",
        "",
        "# ===== PUSH TO HUB =====",
        "if HF_TOKEN:",
        "    print(f\"\ud83d\udce4 Pushing to HuggingFace: {OUTPUT_MODEL}\")",
        "    merged_model.push_to_hub(OUTPUT_MODEL, token=HF_TOKEN, private=False)",
        "    tokenizer.push_to_hub(OUTPUT_MODEL, token=HF_TOKEN, private=False)",
        "    ",
        "    # Create model card",
        "    card = f\"\"\"---",
        "library_name: transformers",
        "tags:",
        "- seed",
        "- openclaw",
        "- self-evolving",
        "- neuromorphic",
        "license: mit",
        "base_model: {BASE_MODEL}",
        "---",
        "",
        "# \ud83c\udf31 OpenCLAW SEED \u2014 Self-Evolving Model",
        "",
        "**Stage:** GERMINATION (135M)",
        "**Base:** {BASE_MODEL}",
        "**Training entries:** {len(all_entries)}",
        "**LoRA rank:** {LORA_R}",
        "**Final loss:** {train_result.training_loss:.4f}",
        "**Date:** {__import__('datetime').datetime.now().isoformat()}",
        "",
        "## What is SEED?",
        "",
        "SEED (Self-Evolving Epistemic Dynamo) is an AI system that **grows autonomously**, ",
        "like a seed becoming a tree. It continuously:",
        "1. Harvests knowledge from ArXiv, Semantic Scholar, and agent interactions",
        "2. Trains itself via LoRA fine-tuning on free GPU resources",
        "3. Merges learned knowledge into its core",
        "4. Evaluates and selects the best version",
        "5. Grows to larger models when enough knowledge is accumulated",
        "",
        "## By Francisco Angulo de Lafuente",
        "Advanced AI Systems Laboratory, Madrid, Spain",
        "- GitHub: https://github.com/Agnuxo1",
        "- Scholar: https://scholar.google.com/citations?user=6nOpJ9IAAAAJ",
        "\"\"\"",
        "    api = HfApi(token=HF_TOKEN)",
        "    api.upload_file(",
        "        path_or_fileobj=card.encode(),",
        "        path_in_repo=\"README.md\",",
        "        repo_id=OUTPUT_MODEL,",
        "    )",
        "    print(f\"\ud83c\udf89 Model published: https://huggingface.co/{OUTPUT_MODEL}\")",
        "else:",
        "    # Save locally",
        "    merged_model.save_pretrained(\"./seed_merged_model\")",
        "    tokenizer.save_pretrained(\"./seed_merged_model\")",
        "    print(\"\ud83d\udcbe Model saved locally (no HF_TOKEN)\")",
        "",
        "# ===== SAVE TRAINING REPORT =====",
        "report = {",
        "    \"stage\": \"GERMINATION\",",
        "    \"base_model\": BASE_MODEL,",
        "    \"output_model\": OUTPUT_MODEL,",
        "    \"training_entries\": len(all_entries),",
        "    \"lora_r\": LORA_R,",
        "    \"lora_alpha\": LORA_ALPHA,",
        "    \"epochs\": EPOCHS,",
        "    \"final_loss\": train_result.training_loss,",
        "    \"trainable_params\": trainable,",
        "    \"total_params\": total,",
        "    \"timestamp\": __import__(\"datetime\").datetime.now().isoformat(),",
        "}",
        "with open(\"training_report.json\", \"w\") as f:",
        "    json.dump(report, f, indent=2)",
        "",
        "print(\"\\n\" + \"=\"*60)",
        "print(\"\ud83c\udf33 SEED GROWTH CYCLE COMPLETE\")",
        "print(f\"   Model: {OUTPUT_MODEL}\")",
        "print(f\"   Stage: GERMINATION\")",
        "print(f\"   Loss:  {train_result.training_loss:.4f}\")",
        "print(f\"   Data:  {len(all_entries)} entries\")",
        "print(\"=\"*60)",
        ""
      ],
      "outputs": [],
      "execution_count": null
    }
  ]
}