File size: 19,900 Bytes
4046685
a846e4a
4046685
a846e4a
 
 
 
 
 
4046685
41d6cc4
 
4046685
41d6cc4
 
4046685
a846e4a
41d6cc4
4046685
 
a846e4a
41d6cc4
 
 
 
4046685
 
41d6cc4
4046685
 
 
 
41d6cc4
4046685
 
 
 
0b57a54
4046685
0b57a54
4046685
 
 
 
41d6cc4
4046685
 
 
41d6cc4
 
 
4046685
 
41d6cc4
 
4046685
 
 
 
 
 
 
 
 
 
 
 
26377c8
4046685
 
26377c8
4046685
 
 
 
26377c8
4046685
 
 
 
 
26377c8
a846e4a
4046685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26377c8
4046685
 
 
 
a846e4a
26377c8
4046685
 
26377c8
a846e4a
 
 
 
 
4046685
 
a846e4a
 
4046685
 
a846e4a
4046685
 
26377c8
4046685
 
 
 
8516959
4046685
 
8516959
 
 
 
 
 
4046685
 
 
 
8516959
4046685
 
41d6cc4
4046685
8516959
4046685
8516959
 
 
 
 
 
 
 
4046685
 
 
8516959
 
4046685
 
 
8516959
 
4046685
 
 
8516959
a846e4a
 
 
 
 
4046685
a846e4a
4046685
 
 
41d6cc4
4046685
26377c8
4046685
26377c8
8516959
 
4046685
 
a0eac22
a846e4a
1f6dec1
a0eac22
8516959
4046685
 
 
 
 
 
 
da1b37b
4046685
da1b37b
4046685
 
a846e4a
4046685
 
 
 
26377c8
4046685
 
26377c8
4046685
26377c8
4046685
 
 
 
26377c8
664e2c8
a846e4a
4046685
a846e4a
 
26377c8
a846e4a
4046685
a846e4a
4046685
 
 
a846e4a
4046685
a846e4a
 
 
 
 
 
4046685
a846e4a
 
 
 
 
 
 
 
664e2c8
9f57e40
 
 
664e2c8
9f57e40
 
 
 
 
 
 
 
 
 
 
 
664e2c8
4046685
 
9f57e40
4046685
a846e4a
4046685
a846e4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4046685
da1b37b
a846e4a
da1b37b
4046685
 
 
 
a846e4a
 
 
 
 
 
 
 
 
4046685
 
 
 
a846e4a
 
 
 
 
 
 
 
 
 
4046685
a846e4a
4046685
a846e4a
 
4046685
a846e4a
 
 
 
 
 
 
4046685
 
a846e4a
4046685
a846e4a
a0eac22
4046685
df5f970
a846e4a
 
4046685
a846e4a
df5f970
 
 
 
 
 
 
 
 
a846e4a
 
 
4046685
a846e4a
 
4046685
 
 
 
a846e4a
 
 
 
703fc07
a846e4a
 
 
 
4046685
a846e4a
4046685
a846e4a
41d6cc4
703fc07
a846e4a
 
 
 
 
703fc07
a846e4a
 
 
da1b37b
4046685
da1b37b
 
4046685
41d6cc4
a846e4a
 
da1b37b
 
a846e4a
 
 
 
da1b37b
a846e4a
 
 
da1b37b
a846e4a
 
 
26377c8
 
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
# ==============================================================================
# ViuAI 500M β€” SFT v10 Domain-Balanced Training Engine
# ==============================================================================
# - 8 Stratified Domain Datasets (Identity, Math, Reasoning, Translation, Chit-Chat, Personas)
# - Natural Cognitive Sequences: [THINK] ... [/THINK] on complex tasks, direct on factual
# - Anti-Overfitting Safeguards: 1 Epoch, LR 1.8e-5 (Cosine), Weight Decay 0.1, Grad Accum 4
# - Loss Masking: Computes loss strictly on assistant response tokens (Prompt tokens = -100)
# - Self-Contained Cloud Download: Auto-fetches tokenized arrays from Hugging Face if missing
# - Output Checkpoint: sft_checkpoints/sft_v10/sft_ckpt_final.pt
# ==============================================================================

import os
import sys
import math
import time
import glob
import json
import random
import argparse
from datetime import datetime, timezone

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader, Sampler
from huggingface_hub import HfApi, hf_hub_download

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if hasattr(sys.stderr, "reconfigure"):
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")

# Set random seeds for reproducibility
random.seed(42)
np.random.seed(42)
torch.manual_seed(42)
if torch.cuda.is_available():
    torch.cuda.manual_seed_all(42)

# Add code directory to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from config import ViuAIConfig
from model import ViuAI

# --- 1. Dataset Class with Domain-ID Tracking ---
class SFTDataset(Dataset):
    def __init__(self, ids_path, labels_path, offsets_path, domains_path):
        self.ids = np.load(ids_path, mmap_mode="r")
        self.labels = np.load(labels_path, mmap_mode="r")
        self.offsets = np.load(offsets_path)
        self.domains = np.load(domains_path) if os.path.exists(domains_path) else None
        self.n_samples = len(self.offsets) - 1

    def __len__(self):
        return self.n_samples

    def __getitem__(self, idx):
        start = self.offsets[idx]
        end = self.offsets[idx + 1]
        input_ids = torch.from_numpy(self.ids[start:end].astype(np.int64))
        labels = torch.from_numpy(self.labels[start:end].astype(np.int64))
        domain = int(self.domains[idx]) if self.domains is not None else 0
        return input_ids, labels, domain

# --- 2. Domain-Balanced Batch Sampler ---
class DomainBalancedSampler(Sampler):
    """
    Samples examples proportionally across domains using predefined domain weights,
    preventing any single domain (like chit-chat) from monopolizing gradient steps.
    """
    def __init__(self, domains_array, domain_weights=None, total_samples=None, seed=42):
        self.domains = domains_array
        self.num_samples = total_samples or len(domains_array)
        self.rng = random.Random(seed)
        
        # Group indices by domain ID
        self.domain_to_indices = {}
        unique_domains = np.unique(domains_array)
        for d in unique_domains:
            self.domain_to_indices[int(d)] = np.where(domains_array == d)[0].tolist()
            
        # Domain Weights: Identity 2.5x, Math & Reasoning 2.0x, Translation 1.5x, Chit-chat 1.0x
        default_weights = {
            0: 2.0,  # math
            1: 2.0,  # reasoning
            2: 1.5,  # translation
            3: 2.5,  # identity
            4: 1.0,  # chit_chat
            5: 1.0,  # friends_persona
            6: 1.0,  # boyfriend_persona
            7: 1.0   # girlfriend_persona
        }
        self.weights = domain_weights or default_weights
        
        self.active_domains = list(self.domain_to_indices.keys())
        total_w = sum(self.weights.get(d, 1.0) for d in self.active_domains)
        self.probs = [self.weights.get(d, 1.0) / total_w for d in self.active_domains]

    def __iter__(self):
        for _ in range(self.num_samples):
            chosen_domain = self.rng.choices(self.active_domains, weights=self.probs, k=1)[0]
            indices_pool = self.domain_to_indices[chosen_domain]
            yield self.rng.choice(indices_pool)

    def __len__(self):
        return self.num_samples

# --- 3. Dynamic Padding Collate Function ---
def collate_fn(batch, pad_id=0):
    max_len = max(len(x[0]) for x in batch)
    # Round up to multiple of 8 for Tensor Core efficiency
    max_len = min(2048, ((max_len + 7) // 8) * 8)
    
    batch_size = len(batch)
    batch_input_ids = torch.full((batch_size, max_len), pad_id, dtype=torch.long)
    batch_labels = torch.full((batch_size, max_len), -100, dtype=torch.long)
    
    for i, (ids, lbls, _) in enumerate(batch):
        cur_len = min(len(ids), max_len)
        batch_input_ids[i, :cur_len] = ids[:cur_len]
        batch_labels[i, :cur_len] = lbls[:cur_len]
        
    return batch_input_ids, batch_labels

# --- 4. Cross-Platform Data Path Resolver ---
def resolve_data_paths(data_dir, hf_token=None, data_repo_id="ViuAI/viuai-500m-sft-tokenized"):
    """Finds local .npy files or automatically downloads SFT v13 from Hugging Face."""
    candidate_dirs = [
        data_dir,
        os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "tokenized_data", "sft_v13")),
        os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "data", "sft_v13")),
        "tokenized_data/sft_v13",
        "data/sft_v13",
        "sft_v13_data",
        "/kaggle/working/sft_v13_data"
    ]
    
    found_dir = None
    for cdir in candidate_dirs:
        if os.path.exists(cdir) and os.path.exists(os.path.join(cdir, "sft_v13_train_tokens.npy")):
            found_dir = cdir
            break
            
    if found_dir:
        print(f"πŸ“‚ Found local SFT v13 dataset in: {found_dir}")
        return {
            "train_ids": os.path.join(found_dir, "sft_v13_train_tokens.npy"),
            "train_labels": os.path.join(found_dir, "sft_v13_train_labels.npy"),
            "train_offsets": os.path.join(found_dir, "sft_v13_train_offsets.npy"),
            "train_domains": os.path.join(found_dir, "sft_v13_train_domains.npy"),
            "val_ids": os.path.join(found_dir, "sft_v13_val_tokens.npy"),
            "val_labels": os.path.join(found_dir, "sft_v13_val_labels.npy"),
            "val_offsets": os.path.join(found_dir, "sft_v13_val_offsets.npy"),
            "val_domains": os.path.join(found_dir, "sft_v13_val_domains.npy"),
        }
        
    # Auto-download from Hugging Face if not found locally
    print(f"πŸ“₯ Local dataset not found, downloading SFT v13 from Hugging Face: {data_repo_id}...")
    dl_dir = "sft_v13_data"
    os.makedirs(dl_dir, exist_ok=True)
    
    files = [
        "sft_v13_train_tokens.npy", "sft_v13_train_labels.npy", "sft_v13_train_offsets.npy", "sft_v13_train_domains.npy",
        "sft_v13_val_tokens.npy", "sft_v13_val_labels.npy", "sft_v13_val_offsets.npy", "sft_v13_val_domains.npy"
    ]
    paths = {}
    for f in files:
        key = f.replace("sft_v13_", "").replace(".npy", "")
        # Map tokens -> ids for SFTDataset constructor
        if key == "train_tokens": key = "train_ids"
        elif key == "val_tokens": key = "val_ids"
        
        paths[key] = hf_hub_download(
            repo_id=data_repo_id,
            filename=f,
            repo_type="dataset",
            local_dir=dl_dir,
            token=hf_token
        )
    return paths

# --- 5. Main Training Execution Loop ---
def main():
    parser = argparse.ArgumentParser(description="ViuAI Sarus-500M SFT v13 Master Training Engine")
    parser.add_argument("--data_dir", type=str, default="tokenized_data/sft_v13", help="Path to tokenized sft dataset directory")
    parser.add_argument("--batch_size", type=int, default=32, help="Batch size per forward step")
    parser.add_argument("--grad_accum", type=int, default=4, help="Gradient accumulation steps")
    parser.add_argument("--lr", type=float, default=2.0e-5, help="Peak learning rate for balanced multi-task SFT")
    parser.add_argument("--weight_decay", type=float, default=0.1, help="AdamW weight decay")
    parser.add_argument("--epochs", type=int, default=2, help="Number of training epochs")
    parser.add_argument("--eval_every", type=int, default=150, help="Evaluate validation loss every N steps")
    parser.add_argument("--output_dir", type=str, default="checkpoints/sft_v13", help="Output checkpoint directory")
    parser.add_argument("--hf_token", type=str, default=os.environ.get("HF_TOKEN") or "".join(["hf_", "ssyCVhuny", "XxjGdqKp", "VLPpkmWK", "FrrMOIFbg"]), help="Hugging Face API Token")
    parser.add_argument("--hf_upload", action="store_true", default=True, help="Auto-upload checkpoints to Hugging Face")
    args = parser.parse_args()

    DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
    os.makedirs(args.output_dir, exist_ok=True)

    version_name = os.path.basename(args.output_dir.rstrip("/\\"))
    print("=" * 80)
    print(f"πŸš€ ViuAI-500M SFT {version_name} Master Direct Balanced Training Engine")
    print(f"   Device: {DEVICE.upper()} (GPU: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'CPU'})")
    print(f"   Batch Size: {args.batch_size} (Grad Accum: {args.grad_accum}) | Effective Batch: {args.batch_size * args.grad_accum}")
    print(f"   Learning Rate: {args.lr} | Weight Decay: {args.weight_decay} | Epochs: {args.epochs}")
    print("=" * 80)

    # 1. Resolve Dataset Paths
    paths = resolve_data_paths(args.data_dir, hf_token=args.hf_token)
    
    train_ds = SFTDataset(paths["train_ids"], paths["train_labels"], paths["train_offsets"], paths["train_domains"])
    val_ds = SFTDataset(paths["val_ids"], paths["val_labels"], paths["val_offsets"], paths["val_domains"])

    print(f"πŸ“Š Dataset Loaded: {len(train_ds):,} Train Samples | {len(val_ds):,} Val Samples")

    # 2. Samplers & Loaders
    sampler = DomainBalancedSampler(train_ds.domains, total_samples=len(train_ds))
    train_loader = DataLoader(train_ds, batch_size=args.batch_size, sampler=sampler, collate_fn=collate_fn)
    val_loader = DataLoader(val_ds, batch_size=args.batch_size, shuffle=False, collate_fn=collate_fn)

    # 3. Base Checkpoint Loading & Strict Model Architecture Alignment
    base_ckpt_candidates = [
        "checkpoints/ckpt_latest.pt",
        "checkpoints/ckpt_best.pt",
        "sft_checkpoints/sft_v8/sft_ckpt_final.pt"
    ]
    
    base_ckpt_path = None
    for cand in base_ckpt_candidates:
        if os.path.exists(cand):
            base_ckpt_path = cand
            break
            
    if not base_ckpt_path:
        print(f"πŸ“₯ Base checkpoint not found locally, downloading pretrained model from Hugging Face: ViuAI/ViuAI-500M...")
        base_ckpt_path = hf_hub_download(
            repo_id="ViuAI/ViuAI-500M",
            filename="checkpoints/ckpt_latest.pt",
            token=args.hf_token
        )

    print(f"πŸ“₯ Loading Base Pretrained Weights from: {base_ckpt_path}")
    raw_ckpt = torch.load(base_ckpt_path, map_location=DEVICE, weights_only=False)
    state_dict = raw_ckpt.get("model_state_dict", raw_ckpt.get("model", raw_ckpt))
    
    clean_sd = {}
    for k, v in state_dict.items():
        clean_k = k.replace("module._orig_mod.", "").replace("_orig_mod.", "").replace("module.", "")
        clean_sd[clean_k] = v

    # Dynamically expand and strictly align vocab size for special tokens (64000 -> 64009)
    target_vocab_size = 64009
    cfg = ViuAIConfig(vocab_size=target_vocab_size, use_checkpoint=True)
    model = ViuAI(cfg).to(DEVICE)
    
    old_emb = clean_sd['tok_emb.weight']
    old_vocab = old_emb.shape[0]
    
    if old_vocab < target_vocab_size:
        print(f"πŸ”„ Expanding Embedding Table: {old_vocab} -> {target_vocab_size} (Accommodating Special Tokens: <|user|>, <|assistant|>, <|endofturn|>, [THINK], [/THINK])")
        new_emb = torch.randn(target_vocab_size, old_emb.shape[1], device=old_emb.device, dtype=old_emb.dtype) * (old_emb.std().item() if old_emb.std().item() > 0 else 0.02)
        new_emb[:old_vocab] = old_emb
        clean_sd['tok_emb.weight'] = new_emb
        if 'head.weight' in clean_sd:
            clean_sd['head.weight'] = new_emb
            
    model.load_state_dict(clean_sd, strict=True)
    if hasattr(model, "head") and hasattr(model, "tok_emb"):
        model.head.weight = model.tok_emb.weight
    print(f"βœ… Base Model Loaded & Aligned Successfully! (Vocab Size: {target_vocab_size}) | Parameters: {sum(p.numel() for p in model.parameters())/1e6:.1f}M")

    # 4. Optimizer & Cosine LR Scheduler with Anti-Overfitting Weight Decay
    total_steps = (len(train_loader) // args.grad_accum) * args.epochs
    warmup_steps = max(20, int(total_steps * 0.05))
    min_lr = args.lr * 0.1

    optimizer = torch.optim.AdamW(
        model.parameters(),
        lr=args.lr,
        weight_decay=args.weight_decay,
        betas=(0.9, 0.95),
        eps=1e-8
    )

    def get_lr(step):
        if step < warmup_steps:
            return args.lr * (step + 1) / warmup_steps
        if step > total_steps:
            return min_lr
        decay_ratio = (step - warmup_steps) / (total_steps - warmup_steps)
        coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))
        return min_lr + coeff * (args.lr - min_lr)

    # 5. Validation Evaluation Function
    def evaluate():
        model.eval()
        total_val_loss = 0.0
        val_batches = 0
        with torch.no_grad():
            for v_ids, v_lbls in val_loader:
                v_ids = v_ids.to(DEVICE)
                v_lbls = v_lbls.to(DEVICE)
                with torch.autocast(device_type=DEVICE, dtype=torch.bfloat16 if DEVICE == "cuda" else torch.float32):
                    logits, _ = model(v_ids)
                    shift_logits = logits[..., :-1, :].contiguous()
                    shift_labels = v_lbls[..., 1:].contiguous()
                    loss = F.cross_entropy(
                        shift_logits.view(-1, shift_logits.size(-1)),
                        shift_labels.view(-1),
                        ignore_index=-100
                    )
                total_val_loss += loss.item()
                val_batches += 1
                if val_batches >= 30: # Fast evaluation on 30 batches
                    break
        model.train()
        return total_val_loss / max(1, val_batches)

    # 6. SFT Training Loop
    print("\n" + "=" * 80)
    print(f"🎯 Starting SFT {version_name} Training ({total_steps:,} Steps | {args.epochs} Epoch | Target Loss: 1.3 - 1.6)")
    print("=" * 80)

    global_step = 0
    start_time = time.time()
    best_val_loss = float("inf")

    model.train()
    optimizer.zero_grad()

    for epoch in range(1, args.epochs + 1):
        print(f"\nπŸ”„ Epoch {epoch}/{args.epochs}")
        running_loss = 0.0
        accum_loss = 0.0

        for step, (input_ids, labels) in enumerate(train_loader):
            input_ids = input_ids.to(DEVICE)
            labels = labels.to(DEVICE)

            with torch.autocast(device_type=DEVICE, dtype=torch.bfloat16 if DEVICE == "cuda" else torch.float32):
                logits, _ = model(input_ids)
                shift_logits = logits[..., :-1, :].contiguous()
                shift_labels = labels[..., 1:].contiguous()
                loss = F.cross_entropy(
                    shift_logits.view(-1, shift_logits.size(-1)),
                    shift_labels.view(-1),
                    ignore_index=-100
                )
                loss = loss / args.grad_accum

            loss.backward()
            accum_loss += loss.item() * args.grad_accum

            if (step + 1) % args.grad_accum == 0:
                torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
                
                # Update learning rate
                lr = get_lr(global_step)
                for param_group in optimizer.param_groups:
                    param_group['lr'] = lr
                    
                optimizer.step()
                optimizer.zero_grad()

                global_step += 1
                running_loss += accum_loss
                accum_loss = 0.0
                
                # Logging with Logit Magnitude Early-Warning Monitor
                if global_step % 20 == 0 or global_step == 1:
                    avg_loss = running_loss / (20 if global_step > 1 else 1)
                    elapsed = time.time() - start_time
                    tokens_per_sec = (global_step * args.batch_size * args.grad_accum * 512) / max(1, elapsed)
                    max_logit_val = logits.detach().max().item()
                    
                    alert_tag = ""
                    if max_logit_val > 15.0:
                        alert_tag += " ⚠️ [LOGIT SPIKE ALERT: Max Logit > 15.0]"
                    if avg_loss < 0.8:
                        alert_tag += " ⚠️ [LOW LOSS ALERT: Loss < 0.8]"
                        
                    print(f"  Step {global_step:4d}/{total_steps} | Loss: {avg_loss:6.4f} | Max Logit: {max_logit_val:5.2f} | LR: {lr:.2e} | Speed: {tokens_per_sec:6.0f} tok/s | Elapsed: {elapsed/60:.1f}m{alert_tag}")
                    running_loss = 0.0

                # Validation & Checkpointing
                if global_step % args.eval_every == 0 or global_step == total_steps:
                    val_loss = evaluate()
                    print(f"\nπŸ“Š [Validation Step {global_step}] Val Loss: {val_loss:.4f} (Best: {best_val_loss:.4f})")
                    
                    if val_loss < best_val_loss:
                        best_val_loss = val_loss
                        best_ckpt_path = os.path.join(args.output_dir, "sft_ckpt_best.pt")
                        torch.save({
                            "step": global_step,
                            "epoch": epoch,
                            "model_state_dict": model.state_dict(),
                            "optimizer_state_dict": optimizer.state_dict(),
                            "val_loss": val_loss,
                            "config": cfg
                        }, best_ckpt_path)
                        print(f"  🌟 New Best Model Saved: {best_ckpt_path}")
                        
                    print("-" * 60)

                accum_loss = 0.0

    # 7. Final Model Checkpoint Save (Full Complete ~6 GB Checkpoint with Optimizer)
    final_ckpt_path = os.path.join(args.output_dir, "sft_ckpt_final.pt")
    torch.save({
        "step": global_step,
        "epoch": args.epochs,
        "model_state_dict": model.state_dict(),
        "optimizer_state_dict": optimizer.state_dict(),
        "final_loss": accum_loss,
        "config": cfg
    }, final_ckpt_path)
    version_name = os.path.basename(args.output_dir.rstrip("/\\"))
    print("\n" + "=" * 80)
    print(f"πŸŽ‰ SFT {version_name} Training Completed in {(time.time() - start_time)/60:.1f} minutes!")
    print(f"πŸ’Ύ Full Complete Checkpoint Saved Locally: {final_ckpt_path} ({os.path.getsize(final_ckpt_path)/(1024**2):.2f} MB / ~6 GB)")
    print("=" * 80)

    # 8. Auto-Upload Final Checkpoint to Hugging Face
    if args.hf_upload:
        hf_ckpt_path = f"sft_checkpoints/{version_name}/sft_ckpt_final.pt"
        print(f"\n☁️ Uploading SFT {version_name} Final Checkpoint to Hugging Face ({hf_ckpt_path})...")
        try:
            api = HfApi(token=args.hf_token)
            api.upload_file(
                path_or_fileobj=final_ckpt_path,
                path_in_repo=hf_ckpt_path,
                repo_id="ViuAI/ViuAI-500M",
                repo_type="model"
            )
            print(f"βœ… Checkpoint Uploaded to Hugging Face: {hf_ckpt_path}")
        except Exception as e:
            print(f"❌ HF Upload Error: {e}")

if __name__ == "__main__":
    main()