mcpField
M
mlx

mlx

github.com/itsmostafa开发2495 次安装25 周前更新
代码仓库

关于 mlx

mlx 是面向 Apple Silicon 的 MLX-LM 技能,介绍如何运行、转换和微调 LLM。适合在 macOS 上开发本地模型工作流的开发者,涵盖生成、量化与服务部署。

主要功能

  1. 01本地文本与批量生成
  2. 02交互式命令行聊天
  3. 03模型转换与量化
  4. 04LoRA 与 QLoRA 微调
  5. 05启动兼容 OpenAI 的服务

适用场景

  1. 01在 Apple Silicon 上运行 LLM
  2. 02将 Hugging Face 模型转换为 MLX 格式
  3. 03用 LoRA 适配模型
  4. 04通过本地 API 提供模型服务

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/itsmostafa/llm-engineering-skills --skill mlx

安装后在 Claude Code 中输入/mlx确认已加载。

附带文件reference/fine-tuning.mdreference/quantization.md

详细介绍

在 Apple Silicon 上使用 MLX 运行大模型

MLX-LM 是一个用于在 Apple Silicon 上运行大模型的 Python 软件包,借助 MLX 框架和统一内存架构实现优化性能。

目录

核心概念

为什么选择 MLX
方面Mac 上的 PyTorchMLX
内存CPU/GPU 副本相互分离统一内存,无需复制
优化通用 Metal 后端原生支持 Apple Silicon
模型加载较慢,占用更多内存延迟加载,高效
量化支持有限内置 4/8 位量化

MLX 数组位于共享内存中,CPU 和 GPU 均可访问,无需承担数据传输开销。

支持的模型

MLX-LM 支持大多数热门架构:Llama、Mistral、Qwen、Phi、Gemma、Cohere 等。请在 Hugging Face 上查看 mlx-community 中预先转换的模型。

安装

pip install mlx-lm

需要 macOS 13.5+ 和 Apple Silicon(M1/M2/M3/M4)。

文本生成

Python API
from mlx_lm import load, generate

# Load model (from HF hub or local path)
model, tokenizer = load("mlx-community/Llama-3.2-3B-Instruct-4bit")

# Generate text
response = generate(
    model,
    tokenizer,
    prompt="Explain quantum computing in simple terms:",
    max_tokens=256,
    temp=0.7,
)
print(response)
流式生成
from mlx_lm import load, stream_generate

model, tokenizer = load("mlx-community/Mistral-7B-Instruct-v0.3-4bit")

prompt = "Write a haiku about programming:"
for response in stream_generate(model, tokenizer, prompt, max_tokens=100):
    print(response.text, end="", flush=True)
print()
批量生成
from mlx_lm import load, batch_generate

model, tokenizer = load("mlx-community/Qwen2.5-7B-Instruct-4bit")

prompts = [
    "What is machine learning?",
    "Explain neural networks:",
    "Define deep learning:",
]

responses = batch_generate(
    model,
    tokenizer,
    prompts,
    max_tokens=100,
)

for prompt, response in zip(prompts, responses):
    print(f"Q: {prompt}\nA: {response}\n")
CLI 生成
# Basic generation
mlx_lm.generate --model mlx-community/Llama-3.2-3B-Instruct-4bit \
    --prompt "Explain recursion:" \
    --max-tokens 256

# With sampling parameters
mlx_lm.generate --model mlx-community/Mistral-7B-Instruct-v0.3-4bit \
    --prompt "Write a poem about AI:" \
    --temp 0.8 \
    --top-p 0.95

交互式聊天

CLI 聊天
# Start chat REPL (context preserved between turns)
mlx_lm.chat --model mlx-community/Llama-3.2-3B-Instruct-4bit
Python 聊天
from mlx_lm import load, generate

model, tokenizer = load("mlx-community/Llama-3.2-3B-Instruct-4bit")

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What's the capital of France?"},
]

prompt = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True
)

response = generate(model, tokenizer, prompt=prompt, max_tokens=256)
print(response)

模型转换

将 Hugging Face 模型转换为 MLX 格式:

CLI 转换
# Convert with 4-bit quantization
mlx_lm.convert --model meta-llama/Llama-3.2-3B-Instruct \
    -q  # Quantize to 4-bit

# With specific quantization
mlx_lm.convert --model mistralai/Mistral-7B-Instruct-v0.3 \
    -q \
    --q-bits 8 \
    --q-group-size 64

# Upload to Hugging Face Hub
mlx_lm.convert --model meta-llama/Llama-3.2-1B-Instruct \
    -q \
    --upload-repo your-username/Llama-3.2-1B-Instruct-4bit-mlx
Python 转换
from mlx_lm import convert

repo = "meta-llama/Llama-3.2-3B-Instruct"
convert(
    repo,
    quantize=True,
    mlx_path="./llama-3.2-3b-mlx",
    q_bits=4,
    q_group_size=64,
)
转换选项
选项默认值说明
--q-bits4量化位数(4 或 8)
--q-group-size64量化的分组大小
--dtypefloat16非量化权重的数据类型

量化

MLX 支持多种量化方法,以适用于不同场景:

方法最适用于命令
Basic快速转换mlx_lm.convert -q
DWQ保持质量mlx_lm.dwq
AWQ感知激活值mlx_lm.awq
Dynamic逐层设置精度mlx_lm.dynamic_quant
GPTQ成熟的方法mlx_lm.gptq
快速量化
# 4-bit quantization during conversion
mlx_lm.convert --model mistralai/Mistral-7B-v0.3 -q

# 8-bit for higher quality
mlx_lm.convert --model mistralai/Mistral-7B-v0.3 -q --q-bits 8

有关各方法的详细介绍,请参阅 reference/quantization.md。

使用 LoRA 微调

MLX 支持 LoRA 和 QLoRA 微调,可在 Apple Silicon 上高效进行适配。

快速入门
pip install "mlx-lm[train]"

# Prepare training data (JSONL format)
# ./data/train.jsonl is required for --train
# ./data/valid.jsonl is optional
# Supported rows include {"text": "..."} and chat {"messages": [...]}

# Fine-tune with LoRA
mlx_lm.lora --model mlx-community/Llama-3.2-3B-Instruct-4bit \
    --train \
    --data ./data \
    --iters 1000

# Completion-only loss for chat/completion datasets
mlx_lm.lora --model mlx-community/Llama-3.2-3B-Instruct-4bit \
    --train \
    --data ./data \
    --mask-prompt

# Generate with adapter
mlx_lm.generate --model mlx-community/Llama-3.2-3B-Instruct-4bit \
    --adapter-path ./adapters \
    --prompt "Your prompt here"
将适配器融合到模型中
# Merge LoRA weights into base model
mlx_lm.fuse --model mlx-community/Llama-3.2-3B-Instruct-4bit \
    --adapter-path ./adapters \
    --save-path ./fused-model

# Or export to GGUF
mlx_lm.fuse --model mlx-community/Llama-3.2-3B-Instruct-4bit \
    --adapter-path ./adapters \
    --export-gguf

有关 LoRA 配置和训练模式的详细信息,请参阅 reference/fine-tuning.md。

当任务需要的容量超过标准 LoRA 时,MLX-LM 还支持 --fine-tune-type dora 和 --fine-tune-type full。

提供模型服务

兼容 OpenAI 的服务端
# Start server
mlx_lm.server --model mlx-community/Llama-3.2-3B-Instruct-4bit --port 8080

# Use with OpenAI client
curl http://localhost:8080/v1/chat/completions \
    -H "Content-Type: application/json" \
    -d '{
        "model": "default",
        "messages": [{"role": "user", "content": "Hello!"}],
        "max_tokens": 256
    }'
Python 客户端
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8080/v1", api_key="not-needed")

response = client.chat.completions.create(
    model="default",
    messages=[{"role": "user", "content": "Explain MLX in one sentence."}],
    max_tokens=100,
)
print(response.choices[0].message.content)

最佳实践

  1. 使用预量化模型:从 Hugging Face 的 mlx-community 下载即可立即使用

  2. 根据硬件选择量化位数:M1/M2 搭配 8GB 内存时使用 4-bit;M2/M3 Pro/Max 为追求质量可使用 8-bit

  3. 充分利用统一内存:与 CUDA 不同,MLX 模型可以使用交换空间,超出“GPU 内存”的容量(速度较慢,但可用)

  4. 使用流式生成提升用户体验:stream_generate 可为交互式应用提供响应迅速的输出

  5. 缓存提示词前缀:对于后缀不同的重复提示词,可使用 mlx_lm.cache_prompt

  6. 限制长文本生成的 KV 缓存:使用 --max-kv-size 限制内存占用,但会影响长距离生成质量

  7. 批量处理相似请求:batch_generate 比依次生成更高效

  8. 从 4-bit 量化开始:质量与体积的平衡较好;如果质量不理想,再升级到 8-bit

  9. 部署时融合适配器:微调完成后,融合适配器可加快推理速度,无需单独加载

  10. 使用活动监视器监控内存:留意内存压力,以避免交换空间频繁读写

  11. 使用聊天模板:对于经过指令微调的模型,始终应用 tokenizer.apply_chat_template()

参考资料

详细文档请参阅 reference/:

  • quantization.md - 详细介绍量化方法及其适用场景
  • fine-tuning.md - 完整的 LoRA/QLoRA 训练指南,涵盖数据格式和配置

外部文档:

评论

支持 Markdown