File size: 28,100 Bytes
93554f7
c7aaa20
e752fd3
 
 
 
 
 
 
dea3286
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d8db9e
 
 
9cffd85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d8db9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dea3286
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e752fd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7828436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7aaa20
 
 
 
 
 
 
 
 
 
 
93554f7
c7aaa20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
{
  "cells": [
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# πŸ” Hugging Face Authentication for Google Colab\n",
        "try:\n",
        "    from google.colab import userdata\n",
        "    import os\n",
        "    hf_token = userdata.get('HF_TOKEN')\n",
        "    os.environ['HUGGINGFACE_HUB_TOKEN'] = hf_token\n",
        "    print('βœ… HF token loaded from Colab secrets')\n",
        "except ImportError:\n",
        "    print('⚠️ Not running in Colab, skipping token setup')\n",
        "except Exception as e:\n",
        "    print(f'⚠️ Could not load HF_TOKEN from Colab secrets: {e}')\n",
        "    print('πŸ’‘ Add HF_TOKEN to Colab secrets: Secrets tab β†’ Add new secret β†’ Name: HF_TOKEN')\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# πŸ”§ Install compatible versions for stable training\n",
        "!pip install -q transformers>=4.36.0 tokenizers>=0.15.0\n",
        "!pip install -q peft>=0.8.0 datasets>=2.16.0 bitsandbytes>=0.42.0 accelerate>=0.26.0 huggingface_hub trl\n",
        "import os; os.environ['TOKENIZERS_PARALLELISM'] = 'false'\n",
        "print('βœ… Compatible HF stack installed')\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# πŸ›‘οΈ Safe loading functions to avoid tokenizer and import errors\n",
        "from transformers import AutoTokenizer, AutoModelForCausalLM\n",
        "\n",
        "def safe_load_tokenizer(model_name, **kwargs):\n",
        "    \"\"\"Load tokenizer with safe defaults\"\"\"\n",
        "    kwargs.setdefault('use_fast', False)\n",
        "    kwargs.setdefault('trust_remote_code', False)\n",
        "    return AutoTokenizer.from_pretrained(model_name, **kwargs)\n",
        "\n",
        "def safe_load_model(model_name, **kwargs):\n",
        "    \"\"\"Load model with safe defaults\"\"\"\n",
        "    kwargs.setdefault('trust_remote_code', False)\n",
        "    return AutoModelForCausalLM.from_pretrained(model_name, **kwargs)\n",
        "\n",
        "print('βœ… Safe loading functions ready')\n",
        "print('πŸ’‘ Use: tokenizer = safe_load_tokenizer(MODEL_NAME)')\n",
        "print('πŸ’‘ Use: model = safe_load_model(MODEL_NAME, quantization_config=bnb_config, device_map=\"auto\")')\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# πŸ” Hugging Face Authentication for Google Colab\n",
        "try:\n",
        "    from google.colab import userdata\n",
        "    import os\n",
        "    hf_token = userdata.get('HF_TOKEN')\n",
        "    os.environ['HUGGINGFACE_HUB_TOKEN'] = hf_token\n",
        "    print('βœ… HF token loaded from Colab secrets')\n",
        "except ImportError:\n",
        "    print('⚠️ Not running in Colab, skipping token setup')\n",
        "except Exception as e:\n",
        "    print(f'⚠️ Could not load HF_TOKEN from Colab secrets: {e}')\n",
        "    print('πŸ’‘ Add HF_TOKEN to Colab secrets: Secrets tab β†’ Add new secret β†’ Name: HF_TOKEN')\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# πŸ”§ Install compatible versions for stable training\n",
        "!pip install -q transformers>=4.36.0 tokenizers>=0.15.0\n",
        "!pip install -q peft>=0.8.0 datasets>=2.16.0 bitsandbytes>=0.42.0 accelerate>=0.26.0 huggingface_hub trl\n",
        "import os; os.environ['TOKENIZERS_PARALLELISM'] = 'false'\n",
        "print('βœ… Compatible HF stack installed')\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# πŸ”„ Clear any previous patches and restart imports\n",
        "import importlib\n",
        "import sys\n",
        "\n",
        "# Clear transformers from cache if it exists\n",
        "if 'transformers' in sys.modules:\n",
        "    del sys.modules['transformers']\n",
        "    print('🧹 Cleared transformers from module cache')\n",
        "\n",
        "# Fresh import\n",
        "from transformers import AutoTokenizer, AutoModelForCausalLM\n",
        "print('βœ… Fresh transformers import - no patches applied')\n",
        "print('πŸ’‘ Use explicit parameters: AutoTokenizer.from_pretrained(model, use_fast=False, trust_remote_code=False)')\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# πŸ” Hugging Face Authentication for Google Colab\n",
        "try:\n",
        "    from google.colab import userdata\n",
        "    import os\n",
        "    hf_token = userdata.get('HF_TOKEN')\n",
        "    os.environ['HUGGINGFACE_HUB_TOKEN'] = hf_token\n",
        "    print('βœ… HF token loaded from Colab secrets')\n",
        "except ImportError:\n",
        "    print('⚠️ Not running in Colab, skipping token setup')\n",
        "except Exception as e:\n",
        "    print(f'⚠️ Could not load HF_TOKEN from Colab secrets: {e}')\n",
        "    print('πŸ’‘ Add HF_TOKEN to Colab secrets: Secrets tab β†’ Add new secret β†’ Name: HF_TOKEN')\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# πŸ”§ Install compatible versions for stable training\n",
        "!pip install -q transformers>=4.36.0 tokenizers>=0.15.0\n",
        "!pip install -q peft>=0.8.0 datasets>=2.16.0 bitsandbytes>=0.42.0 accelerate>=0.26.0 huggingface_hub trl\n",
        "import os; os.environ['TOKENIZERS_PARALLELISM'] = 'false'\n",
        "print('βœ… Compatible HF stack installed')\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# 🩹 Force safe defaults to avoid fast-tokenizer and remote code import issues\n",
        "import transformers\n",
        "from transformers import AutoTokenizer, AutoModelForCausalLM\n",
        "\n",
        "# Store original methods\n",
        "_orig_tok_from_pretrained = AutoTokenizer.from_pretrained.__func__\n",
        "_orig_model_from_pretrained = AutoModelForCausalLM.from_pretrained.__func__\n",
        "\n",
        "# Create safe wrapper functions\n",
        "def safe_tokenizer_from_pretrained(cls, *args, **kwargs):\n",
        "    kwargs.setdefault('use_fast', False)\n",
        "    kwargs.setdefault('trust_remote_code', False)\n",
        "    return _orig_tok_from_pretrained(cls, *args, **kwargs)\n",
        "\n",
        "def safe_model_from_pretrained(cls, *args, **kwargs):\n",
        "    kwargs.setdefault('trust_remote_code', False)\n",
        "    return _orig_model_from_pretrained(cls, *args, **kwargs)\n",
        "\n",
        "# Apply patches\n",
        "AutoTokenizer.from_pretrained = classmethod(safe_tokenizer_from_pretrained)\n",
        "AutoModelForCausalLM.from_pretrained = classmethod(safe_model_from_pretrained)\n",
        "print('βœ… Patched: AutoTokenizer(use_fast=False, trust_remote_code=False) and AutoModel(trust_remote_code=False) by default')\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# πŸ” Hugging Face Authentication for Google Colab\n",
        "try:\n",
        "    from google.colab import userdata\n",
        "    import os\n",
        "    hf_token = userdata.get('HF_TOKEN')\n",
        "    os.environ['HUGGINGFACE_HUB_TOKEN'] = hf_token\n",
        "    print('βœ… HF token loaded from Colab secrets')\n",
        "except ImportError:\n",
        "    print('⚠️ Not running in Colab, skipping token setup')\n",
        "except Exception as e:\n",
        "    print(f'⚠️ Could not load HF_TOKEN from Colab secrets: {e}')\n",
        "    print('πŸ’‘ Add HF_TOKEN to Colab secrets: Secrets tab β†’ Add new secret β†’ Name: HF_TOKEN')\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# πŸ”§ Install pinned versions for stable training\n",
        "!pip install -q transformers==4.46.2 tokenizers==0.20.1\n",
        "!pip install -q peft==0.14.0 datasets==2.20.0 bitsandbytes==0.43.3 accelerate==0.34.2 huggingface_hub==0.24.6 trl==0.11.4\n",
        "import os; os.environ['TOKENIZERS_PARALLELISM'] = 'false'\n",
        "print('βœ… Pinned HF stack installed')\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# 🩹 Force safe defaults to avoid fast-tokenizer and remote code import issues\n",
        "from transformers import AutoTokenizer as _AutoTokenizer, AutoModelForCausalLM as _AutoModelForCausalLM\n",
        "_orig_tok_from_pretrained = _AutoTokenizer.from_pretrained\n",
        "def _patched_tok_from_pretrained(*args, **kwargs):\n",
        "    kwargs.setdefault('use_fast', False)\n",
        "    kwargs.setdefault('trust_remote_code', False)\n",
        "    return _orig_tok_from_pretrained(*args, **kwargs)\n",
        "_AutoTokenizer.from_pretrained = staticmethod(_patched_tok_from_pretrained)\n",
        "\n",
        "_orig_model_from_pretrained = _AutoModelForCausalLM.from_pretrained\n",
        "def _patched_model_from_pretrained(*args, **kwargs):\n",
        "    kwargs.setdefault('trust_remote_code', False)\n",
        "    return _orig_model_from_pretrained(*args, **kwargs)\n",
        "_AutoModelForCausalLM.from_pretrained = staticmethod(_patched_model_from_pretrained)\n",
        "print('βœ… Patched: AutoTokenizer(use_fast=False, trust_remote_code=False) and AutoModel(trust_remote_code=False) by default')\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# πŸ”§ Install pinned versions for stable training\n",
        "!pip install -q transformers==4.46.2 tokenizers==0.20.1\n",
        "!pip install -q peft==0.14.0 datasets==2.20.0 bitsandbytes==0.43.3 accelerate==0.34.2 huggingface_hub==0.24.6 trl==0.11.4\n",
        "import os; os.environ['TOKENIZERS_PARALLELISM'] = 'false'\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# 🩹 Force safe defaults to avoid fast-tokenizer and remote code import issues\n",
        "from transformers import AutoTokenizer as _AutoTokenizer, AutoModelForCausalLM as _AutoModelForCausalLM\n",
        "_orig_tok_from_pretrained = _AutoTokenizer.from_pretrained\n",
        "def _patched_tok_from_pretrained(*args, **kwargs):\n",
        "    kwargs.setdefault('use_fast', False)\n",
        "    kwargs.setdefault('trust_remote_code', False)\n",
        "    return _orig_tok_from_pretrained(*args, **kwargs)\n",
        "_AutoTokenizer.from_pretrained = staticmethod(_patched_tok_from_pretrained)\n",
        "\n",
        "_orig_model_from_pretrained = _AutoModelForCausalLM.from_pretrained\n",
        "def _patched_model_from_pretrained(*args, **kwargs):\n",
        "    kwargs.setdefault('trust_remote_code', False)\n",
        "    return _orig_model_from_pretrained(*args, **kwargs)\n",
        "_AutoModelForCausalLM.from_pretrained = staticmethod(_patched_model_from_pretrained)\n",
        "print('βœ… Patched: AutoTokenizer(use_fast=False, trust_remote_code=False) and AutoModel(trust_remote_code=False) by default')\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# πŸ”§ Install pinned versions for stable training\n",
        "!pip install -q transformers==4.46.2 tokenizers==0.20.1\n",
        "!pip install -q peft==0.14.0 datasets==2.20.0 bitsandbytes==0.43.3 accelerate==0.34.2 huggingface_hub==0.24.6 trl==0.11.4\n",
        "import os; os.environ['TOKENIZERS_PARALLELISM'] = 'false'\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": [
        "# 🩹 Force slow tokenizer by default to avoid PyPreTokenizerTypeWrapper errors\n",
        "from transformers import AutoTokenizer as _AutoTokenizer\n",
        "_orig_from_pretrained = _AutoTokenizer.from_pretrained\n",
        "def _patched_from_pretrained(*args, **kwargs):\n",
        "    kwargs.setdefault('use_fast', False)\n",
        "    return _orig_from_pretrained(*args, **kwargs)\n",
        "_AutoTokenizer.from_pretrained = staticmethod(_patched_from_pretrained)\n",
        "print('βœ… Patched AutoTokenizer.from_pretrained to default use_fast=False')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# 🌟 CELESTIAL MISTRAL 7B TRAINING\n",
        "## Train Your Own Mistral 7B Model for CELESTIAL AI\n",
        "\n",
        "This notebook properly trains Mistral 7B v0.3 with:\n",
        "- 150 production-quality conversations\n",
        "- LoRA fine-tuning for efficiency\n",
        "- Proper chat formatting for Mistral\n",
        "- No logging issues"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# πŸ“¦ INSTALL REQUIRED PACKAGES FOR MISTRAL 7B\n",
        "!pip install -q transformers==4.36.0 datasets accelerate peft bitsandbytes huggingface_hub trl\n",
        "\n",
        "# Disable all logging to prevent issues\n",
        "import os\n",
        "import warnings\n",
        "os.environ[\"WANDB_DISABLED\"] = \"true\"\n",
        "os.environ[\"WANDB_MODE\"] = \"disabled\"\n",
        "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n",
        "warnings.filterwarnings('ignore')\n",
        "\n",
        "print('βœ… Packages installed for Mistral 7B training!')\n",
        "print('🚫 All logging disabled to prevent errors')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# πŸ”‘ HUGGINGFACE AUTHENTICATION\n",
        "from huggingface_hub import notebook_login\n",
        "\n",
        "print('πŸ” Authenticating with HuggingFace for Mistral access...')\n",
        "try:\n",
        "    notebook_login()\n",
        "    print('βœ… Authentication successful!')\n",
        "except Exception as e:\n",
        "    print(f'⚠️ Authentication failed: {e}')\n",
        "    print('Please set your HF token manually if needed')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# πŸ“Š LOAD CELESTIAL DATASET\n",
        "from datasets import load_dataset\n",
        "\n",
        "DATASET_REPO = 'dp1812/celestial-comprehensive-spiritual-ai'\n",
        "\n",
        "print('πŸ“Š Loading CELESTIAL dataset for Mistral training...')\n",
        "try:\n",
        "    dataset = load_dataset(DATASET_REPO, data_files='celestial_complete_production_dataset.jsonl', split='train')\n",
        "    print(f'βœ… Dataset loaded: {len(dataset)} conversations')\n",
        "    print('🎯 100 numerology + 50 Krishna divine guidance')\n",
        "except Exception as e:\n",
        "    print(f'❌ Dataset loading failed: {e}')\n",
        "    # Fallback\n",
        "    try:\n",
        "        dataset = load_dataset(DATASET_REPO, split='train')\n",
        "        print(f'βœ… Fallback dataset loaded: {len(dataset)} conversations')\n",
        "    except Exception as e2:\n",
        "        print(f'❌ All dataset loading failed: {e2}')\n",
        "        raise\n",
        "\n",
        "# Show sample\n",
        "print('\\nπŸ“ Sample conversation:')\n",
        "sample = dataset[0]\n",
        "print(f\"User: {sample['messages'][1]['content'][:60]}...\")\n",
        "print(f\"Assistant: {sample['messages'][2]['content'][:60]}...\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# πŸ€– LOAD MISTRAL 7B MODEL AND TOKENIZER\n",
        "from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig\n",
        "import torch\n",
        "\n",
        "MODEL_NAME = 'mistralai/Mistral-7B-v0.3'\n",
        "\n",
        "print('πŸ€– Loading Mistral 7B v0.3 model and tokenizer...')\n",
        "\n",
        "# Load tokenizer with proper settings\n",
        "tokenizer = AutoTokenizer.from_pretrained(\n",
        "    MODEL_NAME,\n",
        "    trust_remote_code=True,\n",
        "    padding_side='right'\n",
        ")\n",
        "\n",
        "# Add pad token if missing\n",
        "if tokenizer.pad_token is None:\n",
        "    tokenizer.pad_token = tokenizer.eos_token\n",
        "    tokenizer.pad_token_id = tokenizer.eos_token_id\n",
        "\n",
        "# Quantization config for efficient training\n",
        "bnb_config = BitsAndBytesConfig(\n",
        "    load_in_4bit=True,\n",
        "    bnb_4bit_quant_type=\"nf4\",\n",
        "    bnb_4bit_compute_dtype=torch.float16,\n",
        "    bnb_4bit_use_double_quant=True\n",
        ")\n",
        "\n",
        "# Load Mistral 7B model\n",
        "model = AutoModelForCausalLM.from_pretrained(\n",
        "    MODEL_NAME,\n",
        "    quantization_config=bnb_config,\n",
        "    device_map=\"auto\",\n",
        "    trust_remote_code=True,\n",
        "    torch_dtype=torch.float16\n",
        ")\n",
        "\n",
        "print('βœ… Mistral 7B model and tokenizer loaded successfully!')\n",
        "print(f'πŸ” Model: {MODEL_NAME}')\n",
        "print(f'πŸ” Tokenizer vocab size: {len(tokenizer)}')\n",
        "print(f'πŸ” Model device: {model.device}')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# πŸ”§ SETUP LORA FOR MISTRAL 7B\n",
        "from peft import LoraConfig, get_peft_model, TaskType, prepare_model_for_kbit_training\n",
        "\n",
        "print('πŸ”§ Setting up LoRA for Mistral 7B training...')\n",
        "\n",
        "# Prepare model for k-bit training\n",
        "model = prepare_model_for_kbit_training(model)\n",
        "\n",
        "# Mistral 7B specific target modules\n",
        "target_modules = [\n",
        "    \"q_proj\",\n",
        "    \"k_proj\", \n",
        "    \"v_proj\",\n",
        "    \"o_proj\",\n",
        "    \"gate_proj\",\n",
        "    \"up_proj\",\n",
        "    \"down_proj\",\n",
        "    \"lm_head\"\n",
        "]\n",
        "\n",
        "print(f'🎯 Target modules for Mistral: {target_modules}')\n",
        "\n",
        "# Create LoRA config optimized for Mistral\n",
        "lora_config = LoraConfig(\n",
        "    r=64,  # Higher rank for better performance\n",
        "    lora_alpha=16,\n",
        "    target_modules=target_modules,\n",
        "    lora_dropout=0.1,\n",
        "    bias=\"none\",\n",
        "    task_type=TaskType.CAUSAL_LM,\n",
        ")\n",
        "\n",
        "# Apply LoRA to Mistral\n",
        "try:\n",
        "    model = get_peft_model(model, lora_config)\n",
        "    model.print_trainable_parameters()\n",
        "    print('βœ… LoRA adapters attached to Mistral 7B!')\n",
        "except Exception as e:\n",
        "    print(f'❌ LoRA setup failed: {e}')\n",
        "    raise\n",
        "\n",
        "print('🎯 Mistral 7B ready for CELESTIAL training!')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# πŸ“ FORMAT DATA FOR MISTRAL CHAT TRAINING\n",
        "def format_for_mistral_chat(example):\n",
        "    \"\"\"Format conversation for Mistral chat training\"\"\"\n",
        "    messages = example['messages']\n",
        "    \n",
        "    # Extract messages\n",
        "    system_msg = messages[0]['content']\n",
        "    user_msg = messages[1]['content']\n",
        "    assistant_msg = messages[2]['content']\n",
        "    \n",
        "    # Mistral chat format\n",
        "    formatted = f\"<s>[INST] {system_msg}\\n\\nUser: {user_msg} [/INST] {assistant_msg}</s>\"\n",
        "    \n",
        "    # Tokenize\n",
        "    tokens = tokenizer(\n",
        "        formatted,\n",
        "        truncation=True,\n",
        "        padding=False,\n",
        "        max_length=2048,  # Mistral context length\n",
        "        return_tensors=None\n",
        "    )\n",
        "    \n",
        "    # Set labels (same as input_ids for causal LM)\n",
        "    tokens['labels'] = tokens['input_ids'].copy()\n",
        "    \n",
        "    return tokens\n",
        "\n",
        "print('πŸ“ Formatting data for Mistral chat training...')\n",
        "formatted_dataset = dataset.map(\n",
        "    format_for_mistral_chat,\n",
        "    remove_columns=dataset.column_names,\n",
        "    desc=\"Formatting for Mistral\"\n",
        ")\n",
        "\n",
        "print(f'βœ… Formatted {len(formatted_dataset)} conversations for Mistral')\n",
        "print('🎯 Using proper Mistral chat format with [INST] tags')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# πŸš€ MISTRAL TRAINING CONFIGURATION\n",
        "from transformers import TrainingArguments, Trainer, DataCollatorForLanguageModeling\n",
        "\n",
        "print('πŸš€ Setting up Mistral 7B training configuration...')\n",
        "\n",
        "# Training arguments optimized for Mistral 7B\n",
        "training_args = TrainingArguments(\n",
        "    output_dir='./celestial-mistral-7b-results',\n",
        "    num_train_epochs=3,\n",
        "    per_device_train_batch_size=1,\n",
        "    gradient_accumulation_steps=16,  # Effective batch size of 16\n",
        "    warmup_steps=50,\n",
        "    learning_rate=2e-4,  # Higher LR for LoRA\n",
        "    fp16=True,\n",
        "    logging_steps=10,\n",
        "    save_steps=100,\n",
        "    eval_strategy='no',\n",
        "    save_strategy='steps',\n",
        "    load_best_model_at_end=False,\n",
        "    report_to=[],  # No external logging\n",
        "    remove_unused_columns=False,\n",
        "    dataloader_drop_last=True,\n",
        "    group_by_length=True,  # Efficient batching\n",
        "    ddp_find_unused_parameters=False\n",
        ")\n",
        "\n",
        "# Data collator for Mistral\n",
        "data_collator = DataCollatorForLanguageModeling(\n",
        "    tokenizer=tokenizer,\n",
        "    mlm=False,\n",
        "    pad_to_multiple_of=8\n",
        ")\n",
        "\n",
        "# Create Mistral trainer\n",
        "trainer = Trainer(\n",
        "    model=model,\n",
        "    args=training_args,\n",
        "    train_dataset=formatted_dataset,\n",
        "    tokenizer=tokenizer,\n",
        "    data_collator=data_collator\n",
        ")\n",
        "\n",
        "print('βœ… Mistral 7B training configuration ready!')\n",
        "print('🎯 Optimized for CELESTIAL AI with LoRA fine-tuning')\n",
        "print('⏱️ Expected training time: 30-45 minutes')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# πŸƒβ€β™‚οΈ START MISTRAL 7B TRAINING\n",
        "print('πŸƒβ€β™‚οΈ Starting CELESTIAL Mistral 7B training...')\n",
        "print('⏱️ Expected time: 30-45 minutes')\n",
        "print('🎯 Training Mistral 7B v0.3 on CELESTIAL conversations')\n",
        "print('πŸ’Ž 150 production-quality conversations')\n",
        "print('\\nπŸš€ Mistral training begins now...')\n",
        "\n",
        "try:\n",
        "    # Start Mistral training\n",
        "    trainer.train()\n",
        "    \n",
        "    print('\\nπŸŽ‰ MISTRAL 7B TRAINING COMPLETED SUCCESSFULLY!')\n",
        "    print('βœ… CELESTIAL Mistral 7B is now trained!')\n",
        "    print('🌟 Ready for testing and deployment!')\n",
        "    \n",
        "except Exception as e:\n",
        "    print(f'❌ Mistral training failed: {e}')\n",
        "    print('πŸ”§ Please check the error and try again')\n",
        "    raise"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# πŸ§ͺ TEST TRAINED MISTRAL 7B\n",
        "print('πŸ§ͺ Testing the trained CELESTIAL Mistral 7B...')\n",
        "\n",
        "model.eval()\n",
        "\n",
        "test_prompts = [\n",
        "    \"<s>[INST] You are CELESTIAL AI, an expert numerologist. Provide detailed analysis.\\n\\nUser: Tell me about number 7 in Chaldean numerology. [/INST]\",\n",
        "    \"<s>[INST] You are Shree Krishna providing divine guidance.\\n\\nUser: Krishna, I need guidance about my career path. [/INST]\",\n",
        "    \"<s>[INST] You are CELESTIAL AI providing numerology analysis.\\n\\nUser: Calculate my numerology for name 'John Smith' born 15/08/1990. [/INST]\"\n",
        "]\n",
        "\n",
        "for i, prompt in enumerate(test_prompts, 1):\n",
        "    print(f'\\nπŸ” Test {i}: Mistral 7B Response')\n",
        "    \n",
        "    try:\n",
        "        inputs = tokenizer(prompt, return_tensors=\"pt\").to(model.device)\n",
        "        \n",
        "        with torch.no_grad():\n",
        "            outputs = model.generate(\n",
        "                **inputs,\n",
        "                max_new_tokens=300,\n",
        "                temperature=0.7,\n",
        "                do_sample=True,\n",
        "                pad_token_id=tokenizer.pad_token_id,\n",
        "                eos_token_id=tokenizer.eos_token_id\n",
        "            )\n",
        "        \n",
        "        response = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
        "        generated = response[len(prompt):].strip()\n",
        "        \n",
        "        print(f'πŸ€– Mistral Response: {generated[:250]}...')\n",
        "        \n",
        "        # Quality check\n",
        "        if len(generated) > 50 and 'number' in generated.lower() or 'krishna' in generated.lower():\n",
        "            print('βœ… Response quality: EXCELLENT')\n",
        "        else:\n",
        "            print('⚠️ Response quality: NEEDS IMPROVEMENT')\n",
        "        \n",
        "    except Exception as e:\n",
        "        print(f'❌ Test {i} failed: {e}')\n",
        "\n",
        "print('\\nπŸŽ‰ CELESTIAL MISTRAL 7B TRAINING COMPLETE!')\n",
        "print('βœ… Your own trained Mistral 7B model is ready!')\n",
        "print('🌟 No external API dependencies - fully yours!')\n",
        "print('\\nπŸš€ Next Steps:')\n",
        "print('   β€’ Save the trained model to HuggingFace')\n",
        "print('   β€’ Integrate with CELESTIAL platform')\n",
        "print('   β€’ Expand training data for more features')\n",
        "print('   β€’ Deploy to production environment')"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.8.5"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 4
}