File size: 5,328 Bytes
6d5c79f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Train a small LLM on a local text corpus inside Docker (CPU or GPU).

This is the budget-friendly trainer for laptop-scale validation. It uses the
same ZenexMoEDecoder architecture as the full model, just smaller.
After training the checkpoint is auto-loaded by the frontend on next start.
"""

from __future__ import annotations

import argparse
import logging
import math
from pathlib import Path

import numpy as np
import torch

from architecture.config import ModelConfig
from architecture.model import ZenexMoEDecoder
from architecture.mtp import compute_mtp_loss

LOGGER = logging.getLogger(__name__)


def build_small_config(vocab_size: int) -> ModelConfig:
    """Small but real config that fits on a laptop CPU."""

    return ModelConfig(
        num_layers=4,
        hidden_size=256,
        num_attention_heads_q=8,
        num_attention_heads_kv=8,
        head_dim=32,
        vocab_size=vocab_size,
        ffn_intermediate_size=512,
        num_routed_experts=8,
        num_shared_experts=1,
        top_k_experts=2,
        mla_kv_latent_dim=128,
        mla_q_latent_dim=128,
        mtp_predict_steps=2,
    )


def load_corpus_as_bytes(corpus_path: Path) -> np.ndarray:
    """Tokenize text as raw bytes - simple, no tokenizer needed."""

    text = corpus_path.read_text(encoding="utf-8", errors="ignore")
    arr = np.frombuffer(text.encode("utf-8"), dtype=np.uint8).astype(np.int64)
    return arr


def get_batch(data: np.ndarray, seq_len: int, batch_size: int, device: torch.device):
    """Sample random contiguous chunks for a training batch."""

    ix = np.random.randint(0, len(data) - seq_len - 1, size=batch_size)
    x = np.stack([data[i : i + seq_len] for i in ix])
    y = np.stack([data[i + 1 : i + seq_len + 1] for i in ix])
    return torch.from_numpy(x).to(device), torch.from_numpy(y).to(device)


def cosine_lr(step: int, total: int, warmup: int, peak: float, min_lr: float) -> float:
    """Cosine decay with warmup."""

    if step < warmup:
        return peak * (step + 1) / max(1, warmup)
    progress = (step - warmup) / max(1, total - warmup)
    return min_lr + 0.5 * (peak - min_lr) * (1 + math.cos(math.pi * progress))


def train(
    corpus_path: Path,
    output_path: Path,
    steps: int,
    seq_len: int,
    batch_size: int,
    peak_lr: float,
    log_every: int,
) -> None:
    """Run a small training loop and checkpoint the result."""

    device = torch.device(
        "cuda" if torch.cuda.is_available()
        else ("mps" if hasattr(torch.backends, "mps") and torch.backends.mps.is_available() else "cpu")
    )
    LOGGER.info("Training on device: %s", device)

    data = load_corpus_as_bytes(corpus_path)
    LOGGER.info("Corpus size: %d bytes", len(data))

    cfg = build_small_config(vocab_size=256)
    model = ZenexMoEDecoder(cfg).to(device)
    n_params = sum(p.numel() for p in model.parameters())
    LOGGER.info("Model size: %.2fM params", n_params / 1e6)

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

    for step in range(steps):
        x, y = get_batch(data, seq_len=seq_len, batch_size=batch_size, device=device)
        lr = cosine_lr(step, steps, warmup=max(10, steps // 20), peak=peak_lr, min_lr=peak_lr * 0.1)
        for pg in optimizer.param_groups:
            pg["lr"] = lr

        optimizer.zero_grad(set_to_none=True)
        out = model(x)
        lm_loss = torch.nn.functional.cross_entropy(
            out.logits[:, :-1, :].reshape(-1, out.logits.size(-1)),
            y[:, :-1].reshape(-1),
        )
        mtp_loss = compute_mtp_loss(out.mtp_logits, y, weight=0.1)
        loss = lm_loss + mtp_loss

        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optimizer.step()

        if step % log_every == 0:
            LOGGER.info(
                "step=%d/%d loss=%.4f lm=%.4f mtp=%.4f lr=%.6f",
                step, steps, loss.item(), lm_loss.item(), mtp_loss.item(), lr,
            )

    output_path.parent.mkdir(parents=True, exist_ok=True)
    torch.save(model.state_dict(), output_path)
    LOGGER.info("Saved checkpoint to %s", output_path)


def parse_args() -> argparse.Namespace:
    """Parse CLI arguments."""

    parser = argparse.ArgumentParser(description="Train a small LLM on a local text corpus")
    parser.add_argument("--corpus", type=Path, required=True, help="Path to training text file")
    parser.add_argument("--output", type=Path, default=Path("/mnt/nas/checkpoints/latest.pt"))
    parser.add_argument("--steps", type=int, default=500)
    parser.add_argument("--seq-len", type=int, default=128)
    parser.add_argument("--batch-size", type=int, default=8)
    parser.add_argument("--lr", type=float, default=3e-4)
    parser.add_argument("--log-every", type=int, default=20)
    return parser.parse_args()


def main() -> None:
    """CLI entrypoint."""

    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
    args = parse_args()
    train(
        corpus_path=args.corpus,
        output_path=args.output,
        steps=args.steps,
        seq_len=args.seq_len,
        batch_size=args.batch_size,
        peak_lr=args.lr,
        log_every=args.log_every,
    )


if __name__ == "__main__":
    main()