Datasets:
Download train_mlx.py from emgena/tool_response_content_hash_cache_mcp_teaser: direct link, hf CLI and curl.
- Browser
- Download file 4.56 kB
-
https://huggingface.co/datasets/emgena/tool_response_content_hash_cache_mcp_teaser/resolve/main/train_mlx.py
- Command line
-
hf download hf://datasets/emgena/tool_response_content_hash_cache_mcp_teaser/train_mlx.py
-
curl -L -o train_mlx.py https://huggingface.co/datasets/emgena/tool_response_content_hash_cache_mcp_teaser/resolve/main/train_mlx.py
4.56 kB
| #!/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() | |