Text Generation
PyTorch
English
microcontrollers
esp32
quantized
edge-ai
File size: 27,163 Bytes
6ea5f42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ==============================================================================
# KryonAI 4M High-Intelligence Trainer & .krai Exporter for KryonOS (ESP32-S3)
# Target: Google Colab L4 GPU (auto-compatible with T4 / A100 / H100)
# Output: KryonOS All-in-One .krai (64B Header + UTF8 Vocab + INT8 SIMD)
# ==============================================================================
# The KryonAI-Text-4M model provided in this repository was trained using this exact script.
!pip install -q torch datasets tokenizers tqdm

import os
import re
import time
import math
import json
import struct
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from datasets import load_dataset
from tokenizers import Tokenizer, models, trainers, pre_tokenizers
from tqdm.auto import tqdm

# ==============================================================================
# 1. MOUNT GOOGLE DRIVE & SET SAVE FOLDER
# ==============================================================================
from google.colab import drive
drive.mount('/content/drive')

DRIVE_SAVE_DIR = "/content/drive/MyDrive/KryonOS-AI-Models/Text-Model/KryonAI-v1.0.0" # Customize this path to your preferred Google Drive directory.
os.makedirs(DRIVE_SAVE_DIR, exist_ok=True)
print(f"[Drive] Checkpoints & .krai exports -> {DRIVE_SAVE_DIR}")

# ==============================================================================
# 2. ARCHITECTURE & TRAINING CONFIGURATION (~4.01M PARAMETERS)
# ==============================================================================
# Keep USE_CLASSIC_KRAI_V1_ARCH = True for 100% plug-and-play compatibility with
# existing KryonOS v3.0.0 C++ WPE+LayerNorm+GELU kernels.
CONFIG = {
    "use_classic_krai_v1_arch": True,
    "magic": 0x4E59524B,          # "KRYN"
    "version": 1,
    "model_type": 0,              # 0: TEXT_TRANSFORMER
    "quant_type": 1,              # 1: INT8
    "dim": 192,                   # Hidden dimension
    "hidden_dim": 768,            # FFN dimension (4 * dim)
    "n_layers": 6,                # 6 Transformer blocks -> ~4.01M total params
    "n_heads": 6,                 # 6 attention heads (head_dim = 32)
    "vocab_size": 4096,           # 4,096 BPE subwords
    "seq_len": 128,               # Max context / KV-cache length
    "dropout": 0.04,
    # High-Intelligence Training Schedule (~245M tokens on L4 GPU)
    "batch_size": 256,
    "target_steps": 7500,         # 7500 * 256 * 128 = 245.76M tokens (~13-16 mins on L4)
    "qat_start_ratio": 0.85,      # INT8 Quantization-Aware Training for last 15% of steps
    "lr": 1.0e-3,
    "min_lr": 5.0e-5,
    "weight_decay": 0.05,
    "warmup_steps": 250,
    "checkpoint_every": 750,      # 10 checkpoints saved to Google Drive
    "seed": 42,
}

SYSTEM_PROMPT = "<|system|>You are KryonAI, the local assistant for KryonOS."
SPECIAL_TOKENS = ["<|system|>", "<|user|>", "<|assistant|>", "<|end|>", "<pad>", "<call:>"]
END_ID = 3
PAD_ID = 4

def set_seed(seed):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)

set_seed(CONFIG["seed"])
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.set_float32_matmul_precision("high")
use_bf16 = torch.cuda.is_available() and torch.cuda.is_bf16_supported()
amp_dtype = torch.bfloat16 if use_bf16 else torch.float16
scaler = torch.amp.GradScaler("cuda", enabled=(amp_dtype == torch.float16))
print(f"[Hardware] GPU: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'CPU'} | Precision: {amp_dtype}")

# ==============================================================================
# 3. HIGH-SIGNAL DATASET CURATION + SYNTHETIC ARITHMETIC CURRICULUM
# ==============================================================================
def clean_text(text):
    text = text.replace("```", " ").replace("**", "").replace("###", "").replace("##", "")
    text = re.sub(r"\s+", " ", text).strip()
    return text

def build_identity_and_reasoning_curriculum():
    pairs = []

    # A. KryonOS Core Identity & Helpful General Chat Anchors
    identity = [
        ("Hi", "Hello! I am KryonAI, your offline assistant on KryonOS. How can I help you today?"),
        ("Hi, who are you?", "I am KryonAI, a lightweight local AI assistant running directly on your KryonOS device."),
        ("Hello!", "Hi there! What can I help you with today?"),
        ("Hey", "Hey! I am KryonAI. Ask me anything or let me know how I can assist you."),
        ("Who are you?", "I am KryonAI, an on-device AI assistant built for KryonOS on the ESP32-S3."),
        ("What is KryonOS?", "KryonOS is an open-source graphical operating system for ESP32 microcontrollers that runs JavaScript apps and local AI."),
        ("Are you connected to the internet?", "No, I run 100% offline on your ESP32-S3 processor and PSRAM without cloud servers."),
        ("How are you?", "I am running smoothly and ready to help! How are you doing today?"),
        ("Thank you!", "You are very welcome! Let me know if you need anything else."),
        ("Thanks", "Happy to help! Feel free to ask another question anytime."),
        ("Tell me a joke.", "Why do programmers prefer dark mode? Because light attracts bugs!"),
        ("Tell me a fun fact about space.", "A day on Venus is longer than a year on Venus because it rotates very slowly on its axis."),
        ("How can I stay focused while studying?", "Break your study time into 25-minute focused sessions, silence phone notifications, and review key notes out loud."),
        ("Give me a quick coding tip.", "Write small, testable functions with clear variable names, and test edge cases early."),
        ("What can you do?", "I can chat offline, answer general knowledge questions, solve math problems, and give quick tips on KryonOS."),
    ]
    pairs.extend(identity * 250)

    # B. 16,000 Clean Direct Arithmetic & Number Logic Pairs (Fixes math hallucinations)
    rng = random.Random(42)
    for _ in range(5000):
        a, b = rng.randint(1, 250), rng.randint(1, 250)
        pairs.append((f"What is {a} + {b}?", f"{a} + {b} is {a + b}."))
    for _ in range(4000):
        a = rng.randint(10, 300)
        b = rng.randint(1, a)
        pairs.append((f"What is {a} - {b}?", f"{a} - {b} is {a - b}."))
    for _ in range(4000):
        a, b = rng.randint(2, 25), rng.randint(2, 25)
        pairs.append((f"What is {a} * {b}?", f"{a} multiplied by {b} is {a * b}."))
    for _ in range(3000):
        b = rng.randint(2, 20)
        ans = rng.randint(2, 25)
        a = b * ans
        pairs.append((f"What is {a} divided by {b}?", f"{a} divided by {b} is {ans}."))

    return pairs

def collect_all_datasets():
    pairs = build_identity_and_reasoning_curriculum()
    print(f"[Dataset 0/3] Built {len(pairs):,} KryonOS identity & direct arithmetic pairs")

    # 1. HuggingFaceTB/smol-smoltalk (Full scan of concise conversational turns)
    print("[Dataset 1/3] Loading HuggingFaceTB/smol-smoltalk...")
    ds_smol = load_dataset("HuggingFaceTB/smol-smoltalk", split="train")
    smol_added = 0
    for row in tqdm(ds_smol, desc="Scanning smol-smoltalk"):
        msgs = row.get("messages", [])
        for i in range(len(msgs) - 1):
            if msgs[i]["role"] == "user" and msgs[i + 1]["role"] == "assistant":
                u = clean_text(msgs[i]["content"])
                a = clean_text(msgs[i + 1]["content"])
                # Filter out code dumps/URLs that degrade 4M general chat fluency
                if (
                    2 <= len(u) <= 200
                    and 4 <= len(a) <= 260
                    and "http://" not in a
                    and "https://" not in a
                ):
                    pairs.append((u, a))
                    smol_added += 1
    print(f"  -> Kept {smol_added:,} clean chat pairs from smol-smoltalk")

    # 2. OpenAssistant/oasst2 (Top-ranked English human Q&A pairs)
    print("[Dataset 2/3] Loading OpenAssistant/oasst2...")
    ds_oasst = load_dataset("OpenAssistant/oasst2", split="train")
    prompts = {
        r["message_id"]: clean_text(r["text"])
        for r in ds_oasst
        if r["lang"] == "en" and r["role"] == "prompter" and not r["deleted"]
    }
    oasst_added = 0
    for r in ds_oasst:
        if (
            r["lang"] == "en"
            and r["role"] == "assistant"
            and r["rank"] == 0
            and not r["deleted"]
            and r["parent_id"] in prompts
        ):
            u = prompts[r["parent_id"]]
            a = clean_text(r["text"])
            if 2 <= len(u) <= 200 and 4 <= len(a) <= 260 and "http" not in a:
                pairs.append((u, a))
                oasst_added += 1
    print(f"  -> Kept {oasst_added:,} human Q&A pairs from oasst2")

    # 3. microsoft/orca-math-word-problems-200k (Keep naturally concise problems only)
    # Skipping truncated multi-paragraph proofs prevents incoherent math word salad
    print("[Dataset 3/3] Loading microsoft/orca-math-word-problems-200k...")
    ds_math = load_dataset("microsoft/orca-math-word-problems-200k", split="train")
    math_added = 0
    for row in tqdm(ds_math, desc="Filtering concise orca-math"):
        q = clean_text(row["question"])
        a = clean_text(row["answer"])
        if 8 <= len(q) <= 170 and 4 <= len(a) <= 210:
            pairs.append((q, a))
            math_added += 1
    print(f"  -> Kept {math_added:,} naturally concise word problems from orca-math")

    random.shuffle(pairs)
    print(f"[Dataset] Total curated candidate pairs: {len(pairs):,}")
    return pairs

raw_pairs = collect_all_datasets()

# ==============================================================================
# 4. TRAIN 4,096-SUBWORD BPE TOKENIZER (Exact KryonOS Whitespace Spec)
# ==============================================================================
def train_kryon_tokenizer(pairs, vocab_size=4096):
    print("[Tokenizer] Training 4,096-vocab BPE tokenizer (Whitespace pre-tokenizer)...")
    tokenizer = Tokenizer(models.BPE(unk_token="<pad>"))
    tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()
    trainer = trainers.BpeTrainer(
        vocab_size=vocab_size,
        special_tokens=SPECIAL_TOKENS,
        min_frequency=3,
        show_progress=True,
    )

    sample_pairs = pairs if len(pairs) <= 250000 else random.sample(pairs, 250000)

    def text_iterator():
        for u, a in sample_pairs:
            yield f"{SYSTEM_PROMPT}<|user|>{u}<|assistant|>{a}<|end|>"

    tokenizer.train_from_iterator(text_iterator(), trainer=trainer)
    tok_path = os.path.join(DRIVE_SAVE_DIR, "kryon_tokenizer.json")
    tokenizer.save(tok_path)
    print(f"[Tokenizer] Saved tokenizer -> {tok_path}")
    return tokenizer

tokenizer = train_kryon_tokenizer(raw_pairs, CONFIG["vocab_size"])

# ==============================================================================
# 5. ENCODE, STRICTLY FILTER <= 128 TOKENS, & MASK PROMPT LOSS
# ==============================================================================
def encode_corpus(pairs, tokenizer, seq_len=128):
    print("[DataPrep] Encoding sequences & verifying clean <|end|> termination <= 128 tokens...")
    xs, ys = [], []

    for u, a in tqdm(pairs, desc="Tokenizing"):
        prompt_str = f"{SYSTEM_PROMPT}<|user|>{u}<|assistant|>"
        full_str = f"{prompt_str}{a}<|end|>"

        prompt_ids = tokenizer.encode(prompt_str).ids
        full_ids = tokenizer.encode(full_str).ids

        # Strictly reject anything exceeding seq_len so <|end|> is ALWAYS learned
        if len(full_ids) > seq_len or len(full_ids) <= len(prompt_ids) + 1:
            continue

        padded = full_ids + [PAD_ID] * (seq_len + 1 - len(full_ids))
        x = padded[:seq_len]
        y = padded[1:seq_len + 1]

        # Mask prompt tokens with -100 so loss only trains on assistant completions
        prompt_len = len(prompt_ids)
        for i in range(seq_len):
            if i < prompt_len - 1 or y[i] == PAD_ID:
                y[i] = -100

        xs.append(x)
        ys.append(y)

    X = torch.tensor(xs, dtype=torch.long)
    Y = torch.tensor(ys, dtype=torch.long)
    print(f"[DataPrep] Final verified sequences: {len(X):,} (~{len(X)*seq_len/1e6:.2f}M padded tokens)")
    return X, Y

X_all, Y_all = encode_corpus(raw_pairs, tokenizer, CONFIG["seq_len"])
del raw_pairs

val_size = max(1024, int(0.015 * len(X_all)))
X_train, Y_train = X_all[:-val_size], Y_all[:-val_size]
X_val, Y_val = X_all[-val_size:], Y_all[-val_size:]

class PackedDataset(Dataset):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __len__(self):
        return len(self.x)
    def __getitem__(self, idx):
        return self.x[idx], self.y[idx]

train_loader = DataLoader(
    PackedDataset(X_train, Y_train),
    batch_size=CONFIG["batch_size"],
    shuffle=True,
    pin_memory=True,
    drop_last=True,
)
val_loader = DataLoader(
    PackedDataset(X_val, Y_val),
    batch_size=CONFIG["batch_size"],
    shuffle=False,
    pin_memory=True,
)

# ==============================================================================
# 6. KRYONOS TRANSFORMER MODEL WITH QAT & LABEL SMOOTHING
# ==============================================================================
class QATLinear(nn.Linear):
    """Linear layer with Straight-Through Estimator (STE) fake INT8 quantization."""
    def __init__(self, in_features, out_features, bias=False):
        super().__init__(in_features, out_features, bias=bias)
        self.qat_enabled = False

    def forward(self, x):
        if self.qat_enabled and self.training:
            max_val = self.weight.abs().max().clamp(min=1e-8)
            scale = max_val / 127.0
            w_q = torch.clamp(torch.round(self.weight / scale), -127, 127) * scale
            w = self.weight + (w_q - self.weight).detach()
            return F.linear(x, w, self.bias)
        return F.linear(x, self.weight, self.bias)

class KryonBlock(nn.Module):
    def __init__(self, dim, hidden_dim, n_heads, dropout):
        super().__init__()
        self.n_heads = n_heads
        self.head_dim = dim // n_heads
        self.ln1 = nn.LayerNorm(dim)
        self.qkv = QATLinear(dim, 3 * dim, bias=False)
        self.proj = QATLinear(dim, dim, bias=False)
        self.ln2 = nn.LayerNorm(dim)
        self.mlp_fc = QATLinear(dim, hidden_dim, bias=False)
        self.mlp_proj = QATLinear(hidden_dim, dim, bias=False)
        self.drop = nn.Dropout(dropout)

    def forward(self, x):
        B, T, C = x.shape
        h = self.ln1(x)
        qkv = self.qkv(h).reshape(B, T, 3, self.n_heads, self.head_dim).permute(2, 0, 3, 1, 4)
        q, k, v = qkv[0], qkv[1], qkv[2]
        attn = F.scaled_dot_product_attention(
            q, k, v, is_causal=True, dropout_p=self.drop.p if self.training else 0.0
        )
        attn = attn.transpose(1, 2).contiguous().reshape(B, T, C)
        x = x + self.drop(self.proj(attn))

        h2 = self.ln2(x)
        mlp = self.mlp_proj(F.gelu(self.mlp_fc(h2)))
        x = x + self.drop(mlp)
        return x

class KryonTransformer(nn.Module):
    def __init__(self, cfg):
        super().__init__()
        self.cfg = cfg
        self.wte = nn.Embedding(cfg["vocab_size"], cfg["dim"])
        self.wpe = nn.Embedding(cfg["seq_len"], cfg["dim"])
        self.drop = nn.Dropout(cfg["dropout"])
        self.blocks = nn.ModuleList([
            KryonBlock(cfg["dim"], cfg["hidden_dim"], cfg["n_heads"], cfg["dropout"])
            for _ in range(cfg["n_layers"])
        ])
        self.ln_f = nn.LayerNorm(cfg["dim"])
        self.lm_head = QATLinear(cfg["dim"], cfg["vocab_size"], bias=False)
        self.apply(self._init_weights)

    def _init_weights(self, m):
        if isinstance(m, (nn.Linear, nn.Embedding)):
            nn.init.normal_(m.weight, mean=0.0, std=0.02)
        elif isinstance(m, nn.LayerNorm):
            nn.init.ones_(m.weight)
            nn.init.zeros_(m.bias)

    def enable_qat(self):
        for m in self.modules():
            if isinstance(m, QATLinear):
                m.qat_enabled = True

    def forward(self, idx, targets=None, label_smoothing=0.0):
        B, T = idx.shape
        pos = torch.arange(0, T, dtype=torch.long, device=idx.device)
        x = self.drop(self.wte(idx) + self.wpe(pos))
        for blk in self.blocks:
            x = blk(x)
        x = self.ln_f(x)
        logits = self.lm_head(x)

        loss = None
        if targets is not None:
            loss = F.cross_entropy(
                logits.view(-1, logits.size(-1)),
                targets.view(-1),
                ignore_index=-100,
                label_smoothing=label_smoothing,
            )
        return logits, loss

raw_model = KryonTransformer(CONFIG).to(device)
total_params = sum(p.numel() for p in raw_model.parameters())
print(f"[Model] KryonTransformer initialized: {total_params:,} parameters (~{total_params/1e6:.2f}M)")

try:
    model = torch.compile(raw_model)
except Exception as e:
    print(f"[Info] torch.compile skipped ({e}), using eager mode.")
    model = raw_model

# ==============================================================================
# 7. ALL-IN-ONE .KRAI v1 EXPORTER (64-Byte Header + UTF8 Vocab + INT8 SIMD)
# ==============================================================================
def quantize_int8(tensor):
    t = tensor.detach().float().cpu().numpy()
    max_val = float(np.max(np.abs(t)))
    scale = max_val / 127.0 if max_val > 1e-8 else 1e-8
    q = np.clip(np.round(t / scale), -127, 127).astype(np.int8)
    return struct.pack("<f", scale) + q.tobytes()

def pack_fp32(tensor):
    return tensor.detach().float().cpu().numpy().astype(np.float32).tobytes()

def export_to_krai(model_obj, tokenizer, cfg, output_path):
    vocab_dict = json.loads(tokenizer.to_str())["model"]["vocab"]
    sorted_vocab = [None] * cfg["vocab_size"]
    for tok, tid in vocab_dict.items():
        if tid < cfg["vocab_size"]:
            sorted_vocab[tid] = tok

    vocab_bytes = bytearray()
    for w in sorted_vocab:
        vocab_bytes.extend((w or "").encode("utf-8") + b"\x00")

    weights_payload = bytearray()
    weights_payload.extend(quantize_int8(model_obj.wte.weight))
    weights_payload.extend(quantize_int8(model_obj.wpe.weight))

    for blk in model_obj.blocks:
        weights_payload.extend(pack_fp32(blk.ln1.weight))
        weights_payload.extend(pack_fp32(blk.ln1.bias))
        weights_payload.extend(quantize_int8(blk.qkv.weight))
        weights_payload.extend(quantize_int8(blk.proj.weight))
        weights_payload.extend(pack_fp32(blk.ln2.weight))
        weights_payload.extend(pack_fp32(blk.ln2.bias))
        weights_payload.extend(quantize_int8(blk.mlp_fc.weight))
        weights_payload.extend(quantize_int8(blk.mlp_proj.weight))

    weights_payload.extend(pack_fp32(model_obj.ln_f.weight))
    weights_payload.extend(pack_fp32(model_obj.ln_f.bias))
    weights_payload.extend(quantize_int8(model_obj.lm_head.weight))

    header_size = 64
    vocab_offset = header_size
    weights_offset = (vocab_offset + len(vocab_bytes) + 15) & ~15
    pad_len = weights_offset - (vocab_offset + len(vocab_bytes))
    num_params = sum(p.numel() for p in model_obj.parameters())

    header = struct.pack(
        "<IHHIIHHHHHHIIIHH20s",
        cfg["magic"],
        cfg["version"],
        cfg["model_type"],
        num_params,
        cfg["quant_type"],
        cfg["dim"],
        cfg["hidden_dim"],
        cfg["n_layers"],
        cfg["n_heads"],
        cfg["vocab_size"],
        cfg["seq_len"],
        vocab_offset,
        weights_offset,
        len(weights_payload),
        0,
        0,
        b"\x00" * 20,
    )

    with open(output_path, "wb") as f:
        f.write(header)
        f.write(vocab_bytes)
        if pad_len > 0:
            f.write(b"\x00" * pad_len)
        f.write(weights_payload)

    size_mb = os.path.getsize(output_path) / (1024 * 1024)
    print(f"[Export] Saved .krai -> {output_path} ({size_mb:.2f} MB)")

# ==============================================================================
# 8. VALIDATION & CLEAN DETOKENIZED CHAT TESTER (Zero Artificial Spaces)
# ==============================================================================
@torch.no_grad()
def compute_val_loss(model_obj):
    model_obj.eval()
    total_loss, batches = 0.0, 0
    for vx, vy in val_loader:
        vx, vy = vx.to(device, non_blocking=True), vy.to(device, non_blocking=True)
        with torch.amp.autocast("cuda", dtype=amp_dtype):
            _, loss = model_obj(vx, vy, label_smoothing=0.0)
        total_loss += loss.item()
        batches += 1
    model_obj.train()
    return total_loss / max(1, batches)

@torch.no_grad()
def test_chat_checkpoint(model_obj, tokenizer, step, val_loss):
    model_obj.eval()
    prompts = [
        "Hi, who are you?",
        "What is KryonOS?",
        "What is 24 + 19?",
        "What is 12 * 8?",
        "How can I stay focused while studying?",
        "Tell me a fun fact about space.",
    ]
    print("\n" + "=" * 76)
    print(f" CHECKPOINT EVAL @ STEP {step} | Val Loss: {val_loss:.4f} | PPL: {math.exp(min(val_loss, 20)):.2f}")
    print("=" * 76)

    for p in prompts:
        full_prompt = f"{SYSTEM_PROMPT}<|user|>{p}<|assistant|>"
        ids = tokenizer.encode(full_prompt).ids
        x = torch.tensor([ids], dtype=torch.long, device=device)
        generated = []

        for _ in range(72):
            if x.size(1) >= CONFIG["seq_len"]:
                break
            logits, _ = model_obj(x)
            next_logits = logits[0, -1, :].float()

            # Repetition penalty (1.25) across recent tokens prevents loops
            for prev_id in set(generated[-24:]):
                if next_logits[prev_id] > 0:
                    next_logits[prev_id] /= 1.25
                else:
                    next_logits[prev_id] *= 1.25

            # Block structural tokens except <|end|>
            for bad_id in [0, 1, 2, 4]:
                next_logits[bad_id] = -1e9

            # Focused Top-K (12) + low temperature (0.45) prevents 4M gibberish
            next_logits = next_logits / 0.45
            top_vals, top_idx = torch.topk(next_logits, 12)
            probs = F.softmax(top_vals, dim=-1)
            next_id = top_idx[torch.multinomial(probs, num_samples=1)].item()

            if next_id == END_ID:
                break
            generated.append(next_id)
            x = torch.cat([x, torch.tensor([[next_id]], device=device)], dim=1)

        # Use tokenizer.decode() so subwords join cleanly without artificial spaces
        reply = tokenizer.decode(generated, skip_special_tokens=True)
        reply = re.sub(r"\s+([,.!?;:'-])", r"\1", reply)
        print(f"User: {p}")
        print(f"KryonAI: {reply}\n")
    print("=" * 76 + "\n")
    model_obj.train()

# ==============================================================================
# 9. REAL-TIME TRAINING LOOP WITH QAT & GOOGLE DRIVE CHECKPOINTS
# ==============================================================================
optimizer = torch.optim.AdamW(
    raw_model.parameters(),
    lr=CONFIG["lr"],
    betas=(0.9, 0.95),
    weight_decay=CONFIG["weight_decay"],
    fused=torch.cuda.is_available(),
)

TARGET_STEPS = CONFIG["target_steps"]
QAT_START_STEP = int(TARGET_STEPS * CONFIG["qat_start_ratio"])

def get_lr(step):
    if step < CONFIG["warmup_steps"]:
        return CONFIG["lr"] * (step + 1) / CONFIG["warmup_steps"]
    progress = (step - CONFIG["warmup_steps"]) / max(1, TARGET_STEPS - CONFIG["warmup_steps"])
    return CONFIG["min_lr"] + 0.5 * (CONFIG["lr"] - CONFIG["min_lr"]) * (1.0 + math.cos(math.pi * progress))

print(f"\n[Train] Training {len(X_train):,} sequences for {TARGET_STEPS:,} steps (~{TARGET_STEPS * CONFIG['batch_size'] * CONFIG['seq_len'] / 1e6:.1f}M tokens)")
global_step = 0
best_val_loss = float("inf")
qat_activated = False
start_time = time.time()
running_loss = 0.0
tokens_seen = 0
t0 = time.time()

pbar = tqdm(total=TARGET_STEPS, desc="Training KryonAI-4M-v2")

while global_step < TARGET_STEPS:
    for bx, by in train_loader:
        if global_step >= TARGET_STEPS:
            break

        if not qat_activated and global_step >= QAT_START_STEP:
            raw_model.enable_qat()
            qat_activated = True
            print(f"\n[QAT] Activated INT8 Quantization-Aware Training at step {global_step}!")

        lr = get_lr(global_step)
        for pg in optimizer.param_groups:
            pg["lr"] = lr

        bx = bx.to(device, non_blocking=True)
        by = by.to(device, non_blocking=True)

        optimizer.zero_grad(set_to_none=True)
        with torch.amp.autocast("cuda", dtype=amp_dtype):
            # Mild 0.03 label smoothing prevents overconfident looping on 4M models
            _, loss = model(bx, by, label_smoothing=0.03)

        scaler.scale(loss).backward()
        scaler.unscale_(optimizer)
        torch.nn.utils.clip_grad_norm_(raw_model.parameters(), 1.0)
        scaler.step(optimizer)
        scaler.update()

        running_loss += loss.item()
        tokens_seen += bx.numel()
        global_step += 1
        pbar.update(1)

        if global_step % 25 == 0:
            dt = time.time() - t0
            tok_sec = tokens_seen / max(dt, 1e-5)
            avg_loss = running_loss / 25.0
            elapsed_min = (time.time() - start_time) / 60.0
            pbar.set_postfix({
                "loss": f"{avg_loss:.4f}",
                "lr": f"{lr:.2e}",
                "tok/s": f"{tok_sec:,.0f}",
                "qat": "ON" if qat_activated else "OFF",
                "min": f"{elapsed_min:.1f}",
            })
            running_loss = 0.0
            tokens_seen = 0
            t0 = time.time()

        if global_step % CONFIG["checkpoint_every"] == 0 or global_step == TARGET_STEPS:
            val_loss = compute_val_loss(raw_model)

            ckpt_path = os.path.join(DRIVE_SAVE_DIR, f"checkpoint_step_{global_step}.pt")
            krai_path = os.path.join(DRIVE_SAVE_DIR, f"kryonai_4m_step_{global_step}.krai")

            torch.save({
                "step": global_step,
                "model_state_dict": raw_model.state_dict(),
                "optimizer_state_dict": optimizer.state_dict(),
                "config": CONFIG,
                "val_loss": val_loss,
            }, ckpt_path)
            print(f"\n[Checkpoint] Saved PyTorch checkpoint -> {ckpt_path}")

            export_to_krai(raw_model, tokenizer, CONFIG, krai_path)

            if val_loss < best_val_loss:
                best_val_loss = val_loss
                best_krai_path = os.path.join(DRIVE_SAVE_DIR, "kryonai_4m_best.krai")
                export_to_krai(raw_model, tokenizer, CONFIG, best_krai_path)
                print(f"[Best Model] New lowest Val Loss ({best_val_loss:.4f}) saved to kryonai_4m_best.krai!")

            test_chat_checkpoint(raw_model, tokenizer, global_step, val_loss)

pbar.close()
print(f"\n[Complete] Training finished in {(time.time() - start_time)/60.0:.1f} mins!")
print(f"[Deploy] Copy '{os.path.join(DRIVE_SAVE_DIR, 'kryonai_4m_best.krai')}' to your ESP32-S3 SD card!")