File size: 4,563 Bytes
f4d1c2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""

EMGENA SENTINEL v3.0 - NATIVE APPLE SILICON (MLX) FINE-TUNING ENGINE

Optimized for Apple M1/M2/M3/M4 (Unified Memory) using Apple's mlx-lm.

Automatically converts chatml_format.jsonl -> ./mlx_data/{train,valid}.jsonl on first run.



Usage:

  python train_mlx.py                  # Verify hardware & parameters

  python train_mlx.py --prepare-only   # Build ./mlx_data/{train,valid}.jsonl and validate

  python train_mlx.py --train          # Prepare data + run Apple Silicon LoRA fine-tuning

"""
import json
import os
import platform
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent


def find_source_jsonl() -> Path:
    for name in ("chatml_format.jsonl", "full_training_dataset.jsonl"):
        p = ROOT / name
        if p.exists() and p.stat().st_size > 0:
            return p
    for p in sorted(ROOT.glob("*.jsonl")):
        if p.stat().st_size > 0:
            return p
    raise FileNotFoundError("No ChatML .jsonl dataset file found in package directory.")


def prepare_mlx_data() -> dict:
    src = find_source_jsonl()
    records = []
    with src.open("r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            row = json.loads(line)
            msgs = row.get("messages")
            if isinstance(msgs, list) and msgs:
                # mlx-lm supports native OpenAI {"messages": [...]} format cleanly
                clean_msgs = [{"role": str(m.get("role", "user")), "content": str(m.get("content", ""))} for m in msgs]
                records.append({"messages": clean_msgs})

    if not records:
        raise ValueError(f"Zero valid ChatML records parsed from {src.name}")

    split_idx = max(1, int(len(records) * 0.9))
    train_rows = records[:split_idx]
    valid_rows = records[split_idx:] or records[-min(10, len(records)):]

    out_dir = ROOT / "mlx_data"
    out_dir.mkdir(parents=True, exist_ok=True)
    with (out_dir / "train.jsonl").open("w", encoding="utf-8") as f:
        for r in train_rows:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")
    with (out_dir / "valid.jsonl").open("w", encoding="utf-8") as f:
        for r in valid_rows:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")

    return {"source": src.name, "train_count": len(train_rows), "valid_count": len(valid_rows), "dir": str(out_dir)}


def get_system_info() -> dict:
    return {
        "os": platform.system(),
        "arch": platform.machine(),
        "is_apple_silicon": (sys.platform == "darwin" and platform.machine() in ("arm64", "aarch64")),
        "python_version": sys.version.split()[0],
    }


def main():
    info = get_system_info()
    print("=================================================================")
    print("🍎 EMGENA SENTINEL v3.0: APPLE SILICON (MLX) TRAINING ENGINE")
    print("=================================================================")
    print(f"• OS / Arch: {info['os']} ({info['arch']}) | Python {info['python_version']}")
    print(f"• Apple Silicon Metal: {'✅ YES' if info['is_apple_silicon'] else '⚠️ Cross-Platform Mode'}")

    if "--prepare-only" in sys.argv or "--train" in sys.argv:
        stats = prepare_mlx_data()
        print(f"✅ Prepared MLX splits from {stats['source']}: train={stats['train_count']}, valid={stats['valid_count']} -> ./mlx_data")
        if "--prepare-only" in sys.argv:
            return

    if "--train" not in sys.argv:
        src = find_source_jsonl()
        print(f"✅ Dataset located: {src.name} | Run '--prepare-only' or '--train' on M1-M4 Mac.")
        return

    if not info["is_apple_silicon"]:
        print("⚠️ Non-Apple Silicon host detected. Run '--train' on an Apple Silicon Mac (M1-M4).")
        return

    try:
        import mlx.core as mx
        print(f"⚡ Apple MLX active: {mx.default_device()}")
    except ImportError:
        print("❌ Install MLX first: pip install mlx mlx-lm")
        sys.exit(1)

    cmd = [
        sys.executable, "-m", "mlx_lm.lora",
        "--model", "mlx-community/Qwen2.5-Coder-7B-Instruct-4bit",
        "--train", "--data", str(ROOT / "mlx_data"),
        "--batch-size", "4", "--lora-layers", "16", "--iters", "600",
        "--learning-rate", "1e-4", "--adapter-path", str(ROOT / "adapters_mlx"),
    ]
    subprocess.run(cmd, check=True)


if __name__ == "__main__":
    main()