123 lines
5.6 KiB
Python
123 lines
5.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Validate local chat examples and run the MLX LM training stages."""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import sys
|
|
|
|
|
|
def validate_dataset(directory):
|
|
previous_splits = {}
|
|
for split in ("train", "valid", "test"):
|
|
path = directory / f"{split}.jsonl"
|
|
count = 0
|
|
with path.open(encoding="utf-8") as examples:
|
|
for line_number, line in enumerate(examples, 1):
|
|
try:
|
|
example = json.loads(line)
|
|
messages = example.get("messages") if isinstance(example, dict) else None
|
|
if not isinstance(messages, list) or len(messages) < 2:
|
|
raise ValueError("expected a messages array with at least two turns")
|
|
if any(
|
|
not isinstance(message, dict)
|
|
or message.get("role") not in ("system", "user", "assistant")
|
|
or not isinstance(message.get("content"), str)
|
|
or not message["content"].strip()
|
|
for message in messages
|
|
):
|
|
raise ValueError("expected system, user, or assistant turns with nonempty text")
|
|
if messages[-1]["role"] != "assistant" or not any(
|
|
message["role"] == "user" for message in messages[:-1]
|
|
):
|
|
raise ValueError("expected a user turn followed by a final assistant answer")
|
|
key = tuple((message["role"], " ".join(message["content"].split())) for message in messages[:-1])
|
|
earlier = previous_splits.setdefault(key, split)
|
|
if earlier != split:
|
|
raise ValueError(f"the same prompt appears in {earlier} and {split}")
|
|
except ValueError as error:
|
|
raise ValueError(f"{path.name}:{line_number}: {error}") from error
|
|
count += 1
|
|
if count == 0:
|
|
raise ValueError(f"{path.name}: add at least one example")
|
|
print(f"{split}: {count} examples", flush=True)
|
|
|
|
|
|
def positive_int(value):
|
|
count = int(value)
|
|
if count < 1:
|
|
raise argparse.ArgumentTypeError("must be positive")
|
|
return count
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
actions = parser.add_subparsers(dest="action", required=True)
|
|
for action in ("validate", "train", "evaluate", "fuse"):
|
|
command = actions.add_parser(action)
|
|
if action != "fuse":
|
|
command.add_argument("--data", required=True, type=Path)
|
|
if action != "validate":
|
|
command.add_argument("--base", required=True, type=Path)
|
|
command.add_argument("--adapter", required=True, type=Path)
|
|
if action == "train":
|
|
command.add_argument("--iters", type=positive_int, default=50)
|
|
command.add_argument("--layers", type=positive_int, default=4)
|
|
if action == "fuse":
|
|
command.add_argument("--out", required=True, type=Path)
|
|
convert = actions.add_parser("convert")
|
|
convert.add_argument("--source", required=True)
|
|
convert.add_argument("--out", required=True, type=Path)
|
|
convert.add_argument("--revision")
|
|
convert.add_argument("--quantize", action="store_true")
|
|
args = parser.parse_args()
|
|
|
|
try:
|
|
if args.action == "convert":
|
|
from mlx_lm.convert import convert as convert_model
|
|
|
|
convert_model(args.source, mlx_path=str(args.out.resolve()), revision=args.revision,
|
|
quantize=args.quantize, q_bits=4 if args.quantize else None)
|
|
return 0
|
|
if args.action != "fuse":
|
|
validate_dataset(args.data.resolve())
|
|
if args.action == "validate":
|
|
return 0
|
|
|
|
base = args.base.resolve()
|
|
adapter = args.adapter.resolve()
|
|
if not (base / "config.json").is_file() or not any(base.glob("*.safetensors")):
|
|
raise ValueError("choose a local MLX model folder with config.json and safetensors weights")
|
|
model = ["--model", str(base), "--adapter-path", str(adapter)]
|
|
if args.action == "train":
|
|
if adapter.exists() or base in adapter.parents:
|
|
raise ValueError("choose a new adapter directory outside the base checkpoint")
|
|
command = ["mlx_lm.lora", *model, "--train", "--data", str(args.data.resolve()),
|
|
"--mask-prompt", "--batch-size", "1", "--num-layers", str(args.layers),
|
|
"--iters", str(args.iters)]
|
|
else:
|
|
if not (adapter / "adapters.safetensors").is_file():
|
|
raise ValueError("choose a trained adapter folder containing adapters.safetensors")
|
|
if args.action == "evaluate":
|
|
command = ["mlx_lm.lora", *model, "--test", "--data", str(args.data.resolve())]
|
|
else:
|
|
out = args.out.resolve()
|
|
if out.exists() or base in out.parents or adapter in out.parents:
|
|
raise ValueError("choose a new output directory outside the base and adapter folders")
|
|
command = ["mlx_lm.fuse", *model, "--save-path", str(out)]
|
|
executable = shutil.which(command[0])
|
|
if executable is None:
|
|
raise FileNotFoundError(f"{command[0]} is missing. Install mlx-lm[train].")
|
|
os.execv(executable, command)
|
|
except (OSError, ValueError) as error:
|
|
print(f"Training workflow: {error}", file=sys.stderr)
|
|
return 1
|
|
except KeyboardInterrupt:
|
|
return 130
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|