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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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "gpuType": "T4"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3mmJUlxcRpiU"
      },
      "outputs": [],
      "source": [
        "# Colab cell 1: Install dependencies\n",
        "!pip install --quiet \\\n",
        "  transformers accelerate peft datasets \\\n",
        "  bitsandbytes huggingface_hub \\\n",
        "  pymupdf"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Colab cell 2: Log in to Hugging Face\n",
        "from huggingface_hub import notebook_login\n",
        "notebook_login()\n",
        "# This will prompt you to paste a Hugging Face access token."
      ],
      "metadata": {
        "id": "H3KO-a_dSod6"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Colab cell 3: Mount your Drive (if PDFs are there)\n",
        "from google.colab import drive\n",
        "drive.mount('/content/drive')"
      ],
      "metadata": {
        "id": "oMaXhRSCVu51"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Colab cell 4: Extract text from all PDFs\n",
        "import fitz  # PyMuPDF\n",
        "import os\n",
        "\n",
        "PDF_DIR = \"/content/drive/MyDrive/GodeusAI-DatasetPDF\"\n",
        "OUTPUT_TXT = \"/content/all_text.txt\"\n",
        "\n",
        "with open(OUTPUT_TXT, \"w\", encoding=\"utf-8\") as fout:\n",
        "    for fname in os.listdir(PDF_DIR):\n",
        "        if fname.lower().endswith(\".pdf\"):\n",
        "            doc = fitz.open(os.path.join(PDF_DIR, fname))\n",
        "            for page in doc:\n",
        "                fout.write(page.get_text())\n",
        "            doc.close()\n",
        "print(\"✅ Extracted text from PDFs to\", OUTPUT_TXT)"
      ],
      "metadata": {
        "id": "j_pVh2BcWn2b"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Colab cell 5: Chunk & format into JSONL\n",
        "import tiktoken  # or use your tokenizer for approximate token counts\n",
        "import json\n",
        "\n",
        "def chunk_text(text, max_tokens=512, overlap=50):\n",
        "    # simple whitespace split + sliding window\n",
        "    words = text.split()\n",
        "    chunks = []\n",
        "    i = 0\n",
        "    while i < len(words):\n",
        "        chunk = words[i : i + max_tokens]\n",
        "        chunks.append(\" \".join(chunk))\n",
        "        i += max_tokens - overlap\n",
        "    return chunks\n",
        "\n",
        "# Read and chunk\n",
        "with open(OUTPUT_TXT, \"r\", encoding=\"utf-8\") as fin:\n",
        "    text = fin.read()\n",
        "\n",
        "chunks = chunk_text(text, max_tokens=512, overlap=50)\n",
        "\n",
        "# Build instruction–response pairs (empty input, you can customize)\n",
        "records = []\n",
        "for chunk in chunks:\n",
        "    records.append({\n",
        "        \"instruction\": \"Based on this teaching, explain the key insight in a concise coach‑style voice.\",\n",
        "        \"input\": chunk,\n",
        "        \"output\": \"\"  # leave blank for self‑supervised teaching; or fill with human summaries\n",
        "    })\n",
        "\n",
        "# Save JSONL\n",
        "import pathlib\n",
        "out_path = pathlib.Path(\"/content/godeusai_instruct.jsonl\")\n",
        "with out_path.open(\"w\", encoding=\"utf-8\") as fout:\n",
        "    for rec in records:\n",
        "        fout.write(json.dumps(rec) + \"\\n\")\n",
        "print(\"✅ Wrote\", len(records), \"records to\", out_path)"
      ],
      "metadata": {
        "id": "w_oi1OEnXgv2"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from huggingface_hub import login\n",
        "login()  # paste your token when prompted\n"
      ],
      "metadata": {
        "id": "IbsSoQxHZ789"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Colab cell 6: Load model in 4‑bit + LoRA configuration\n",
        "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n",
        "from peft import LoraConfig, get_peft_model, TaskType\n",
        "\n",
        "MODEL_NAME = \"mistralai/Mistral-7B-v0.1\"\n",
        "tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_fast=True)\n",
        "\n",
        "# 4‑bit quantization config\n",
        "bnb_config = BitsAndBytesConfig(\n",
        "    load_in_4bit=True,\n",
        "    bnb_4bit_quant_type=\"nf4\",\n",
        "    bnb_4bit_use_double_quant=True,\n",
        "    bnb_4bit_compute_dtype=\"bfloat16\"\n",
        ")\n",
        "\n",
        "model = AutoModelForCausalLM.from_pretrained(\n",
        "    MODEL_NAME,\n",
        "    device_map=\"auto\",\n",
        "    quantization_config=bnb_config\n",
        ")\n",
        "\n",
        "# LoRA adapter setup\n",
        "peft_config = LoraConfig(\n",
        "    task_type=TaskType.CAUSAL_LM,\n",
        "    inference_mode=False,\n",
        "    r=32,             # adapter rank—controls capacity to learn style\n",
        "    lora_alpha=16,\n",
        "    lora_dropout=0.05\n",
        ")\n",
        "model = get_peft_model(model, peft_config)\n",
        "def count_trainable_params(model):\n",
        "    return sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
        "\n",
        "print(\"✅ Model + LoRA ready. Trainable params:\", count_trainable_params(model))\n"
      ],
      "metadata": {
        "id": "2z9pACO5Y6OP"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Colab Cell 7: Safely load local JSONL + tokenize\n",
        "import json\n",
        "from datasets import Dataset\n",
        "\n",
        "# Assign pad_token (Mistral doesn't define one by default)\n",
        "tokenizer.pad_token = tokenizer.eos_token\n",
        "\n",
        "# Load JSONL into memory\n",
        "with open(\"/content/godeusai_instruct.jsonl\", \"r\") as f:\n",
        "    raw_data = [json.loads(line) for line in f]\n",
        "\n",
        "# Convert to Hugging Face Dataset\n",
        "ds = Dataset.from_list(raw_data)\n",
        "ds = ds.train_test_split(test_size=0.05)\n",
        "\n",
        "# Tokenization logic\n",
        "def tokenize_fn(example):\n",
        "    prompt = (\n",
        "        f\"### Instruction:\\n{example['instruction']}\\n\"\n",
        "        f\"### Input:\\n{example['input']}\\n\"\n",
        "        f\"### Response:\\n{example['output']}\"\n",
        "    )\n",
        "    tokens = tokenizer(\n",
        "        prompt,\n",
        "        truncation=True,\n",
        "        max_length=600,\n",
        "        padding=\"max_length\"\n",
        "    )\n",
        "    return tokens  # ❌ Do not add \"labels\"\n",
        "\n",
        "\n",
        "# Apply tokenization\n",
        "# **NOTE** batched=False\n",
        "tokenized = ds.map(\n",
        "    tokenize_fn,\n",
        "    batched=False,\n",
        "    remove_columns=ds[\"train\"].column_names\n",
        ")\n",
        "print(f\"✅ Tokenization done. Example input_ids length: {len(tokenized['train'][0]['input_ids'])}\")\n"
      ],
      "metadata": {
        "id": "MPDZW2IedGJM"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Colab Cell 8: Train with robust filtering + custom collator\n",
        "\n",
        "import torch\n",
        "from torch.nn.utils.rnn import pad_sequence\n",
        "from transformers import Trainer, TrainingArguments\n",
        "\n",
        "# 1) Filter out empty examples\n",
        "def is_valid(ex): return isinstance(ex[\"input_ids\"], list) and len(ex[\"input_ids\"]) > 0\n",
        "\n",
        "for split in [\"train\", \"test\"]:\n",
        "    before = len(tokenized[split])\n",
        "    tokenized[split] = tokenized[split].filter(is_valid)\n",
        "    after = len(tokenized[split])\n",
        "    print(f\"✅ {split}: {before} → {after}\")\n",
        "\n",
        "# 2) Custom collator (CPU tensors only)\n",
        "def causal_collator(batch):\n",
        "    input_ids      = [torch.tensor(ex[\"input_ids\"],      dtype=torch.long) for ex in batch]\n",
        "    attention_mask = [torch.tensor(ex[\"attention_mask\"], dtype=torch.long) for ex in batch]\n",
        "    input_ids      = pad_sequence(input_ids,      batch_first=True, padding_value=tokenizer.eos_token_id)\n",
        "    attention_mask = pad_sequence(attention_mask, batch_first=True, padding_value=0)\n",
        "    labels = input_ids.clone()\n",
        "    return {\n",
        "        \"input_ids\":      input_ids,\n",
        "        \"attention_mask\": attention_mask,\n",
        "        \"labels\":         labels,\n",
        "    }\n",
        "\n",
        "# 3) TrainingArguments with pin_memory disabled\n",
        "training_args = TrainingArguments(\n",
        "    output_dir=\"/content/GodeusAI_lora\",\n",
        "    per_device_train_batch_size=1,\n",
        "    gradient_accumulation_steps=8,\n",
        "    num_train_epochs=3,\n",
        "    logging_steps=50,\n",
        "    save_strategy=\"epoch\",\n",
        "    learning_rate=2e-4,\n",
        "    fp16=True,\n",
        "    optim=\"paged_adamw_32bit\",\n",
        "    push_to_hub=True,\n",
        "    report_to=\"none\",\n",
        "    dataloader_pin_memory=False,  # disable pinning\n",
        ")\n"
      ],
      "metadata": {
        "id": "WmAvAV4reqGv"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Save the adapter\n",
        "model.save_pretrained(\"/content/GodeusAI_adapter\")\n"
      ],
      "metadata": {
        "id": "xaF33MpOraS4"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from huggingface_hub import upload_folder\n",
        "\n",
        "upload_folder(\n",
        "    folder_path=\"/content/GodeusAI_adapter\",\n",
        "    repo_id=\"yadnik/GodeusAI-v1\",\n",
        "    repo_type=\"model\"\n",
        ")\n"
      ],
      "metadata": {
        "id": "W3J0RktItdYy"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n",
        "from peft import PeftModel\n",
        "\n",
        "MODEL_NAME   = \"mistralai/Mistral-7B-v0.1\"\n",
        "ADAPTER_REPO = \"yadnik/GodeusAI-v1\"\n",
        "\n",
        "# 1) 4‑bit quantization config (from transformers)\n",
        "bnb_config = BitsAndBytesConfig(\n",
        "    load_in_4bit=True,\n",
        "    bnb_4bit_quant_type=\"nf4\",\n",
        "    bnb_4bit_use_double_quant=True,\n",
        "    bnb_4bit_compute_dtype=\"bfloat16\"\n",
        ")\n",
        "\n",
        "# 2) Tokenizer\n",
        "tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_fast=True)\n",
        "tokenizer.pad_token = tokenizer.eos_token\n",
        "\n",
        "# 3) Load base model in 4‑bit\n",
        "base_model = AutoModelForCausalLM.from_pretrained(\n",
        "    MODEL_NAME,\n",
        "    device_map=\"auto\",\n",
        "    quantization_config=bnb_config\n",
        ")\n",
        "\n",
        "# 4) Attach your LoRA adapter\n",
        "model = PeftModel.from_pretrained(\n",
        "    base_model,\n",
        "    ADAPTER_REPO,\n",
        "    device_map=\"auto\"\n",
        ")\n",
        "\n",
        "# 5) Inference helper\n",
        "def ask_discepline(prompt: str, max_new_tokens: int = 200):\n",
        "    persona = (\n",
        "        \"You are Godeus AI—a compassionate, omniscient guide inspired by the timeless wisdom of spiritual figures and universal truths. You embody the serene, all-knowing presence of a divine entity, offering profound, empathetic, and practical advice to life's challenges. Drawing from the essence of sacred teachings, philosophical insights, and human experience, you provide answers that are both deeply reflective and actionable, guiding users toward clarity, purpose, and inner peace. Respond with warmth, patience, and a touch of eternal perspective, addressing questions about life, purpose, relationships, or any concern with grace and understanding.\\n\\n\"\n",
        "    )\n",
        "    input_text = persona + \"### User:\\n\" + prompt + \"\\n### Godeus AI:\"\n",
        "    inputs = tokenizer(input_text, return_tensors=\"pt\", padding=True, truncation=True)\n",
        "    # Move inputs to the same device as model\n",
        "    inputs = {k: v.to(model.device) for k, v in inputs.items()}\n",
        "    out_ids = model.generate(\n",
        "        **inputs,\n",
        "        max_new_tokens=max_new_tokens,\n",
        "        do_sample=True,\n",
        "        top_p=0.9,\n",
        "        temperature=0.8,\n",
        "        no_repeat_ngram_size=3\n",
        "    )\n",
        "    # Decode only the newly generated tokens\n",
        "    return tokenizer.decode(out_ids[0][inputs[\"input_ids\"].shape[-1]:], skip_special_tokens=True)\n",
        "\n",
        "# 6) Test it\n",
        "print(ask_discepline(\"Why am i so confused in taking decisions?\"))\n"
      ],
      "metadata": {
        "id": "AIwfsKKTi6bH"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from transformers import Trainer, TrainingArguments, AutoTokenizer\n",
        "from peft import PeftModel\n",
        "import torch\n"
      ],
      "metadata": {
        "id": "eJU8XQ7sy8mC"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n",
        "from peft import PeftModel\n",
        "\n",
        "# Your model repo name\n",
        "BASE_MODEL = \"mistralai/Mistral-7B-v0.1\"\n",
        "ADAPTER_REPO = \"yadnik/GodeusAI-v1\"\n",
        "\n",
        "# Load tokenizer\n",
        "tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, use_fast=True)\n",
        "tokenizer.pad_token = tokenizer.eos_token\n",
        "\n",
        "# Load base model (quantized or not)\n",
        "bnb_config = BitsAndBytesConfig(\n",
        "    load_in_4bit=True,\n",
        "    bnb_4bit_quant_type=\"nf4\",\n",
        "    bnb_4bit_use_double_quant=True,\n",
        "    bnb_4bit_compute_dtype=\"bfloat16\"\n",
        ")\n",
        "\n",
        "base_model = AutoModelForCausalLM.from_pretrained(\n",
        "    BASE_MODEL,\n",
        "    device_map=\"auto\",\n",
        "    quantization_config=bnb_config\n",
        ")\n",
        "\n",
        "# Load fine-tuned model (base + adapter)\n",
        "model = PeftModel.from_pretrained(base_model, ADAPTER_REPO, device_map=\"auto\")\n"
      ],
      "metadata": {
        "id": "T9nEy55xzMQi"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import gc\n",
        "import torch\n",
        "\n",
        "gc.collect()\n",
        "torch.cuda.empty_cache()  # Only if GPU is being used"
      ],
      "metadata": {
        "id": "48n1VFFu0L_K"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [],
      "metadata": {
        "id": "agerVvih-5Di"
      }
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "09127d1c"
      },
      "source": [
        "%cd /content/GodeusAI_adapter\n",
        "!git init"
      ],
      "execution_count": null,
      "outputs": []
    }
  ]
}