在 Apple Silicon Mac 上使用 MLX 框架運行 Google TranslateGemma 翻譯模型。
- Apple Silicon Mac(M1/M2/M3/M4)
- macOS 14.0+
- Python 3.10+
- 約 4GB 可用記憶體
conda create -n translategemma python=3.12 -y
source activate translategemmapip install mlx-lm gradioTranslateGemma 是 gated model,需要先申請存取權限:
- 前往 https://huggingface.co/google/translategemma-4b-it
- 點擊 "Request access" 並同意條款
- 登入 CLI:
huggingface-cli login輸入你的 HF Token(從 https://huggingface.co/settings/tokens 取得)
執行:
python app.py開啟瀏覽器前往 http://127.0.0.1:7860
from mlx_lm import load, generate
# 載入 4-bit 量化模型(約 2GB)
model, tokenizer = load("mlx-community/translategemma-4b-it-4bit")
def translate(text, source_lang="en", target_lang="zh-TW"):
messages = [
{
"role": "user",
"content": [
{
"type": "text",
"source_lang_code": source_lang,
"target_lang_code": target_lang,
"text": text,
}
],
}
]
prompt = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
result = generate(model, tokenizer, prompt=prompt, max_tokens=256)
return result.replace("<end_of_turn>", "").strip()
# 使用範例
print(translate("Hello, how are you?", "en", "zh-TW"))
# 輸出: 你好,你好嗎?python -m mlx_lm.generate \
--model mlx-community/translategemma-4b-it-4bit \
--prompt "Translate English to Chinese: Hello world"| 語言 | 代碼 |
|---|---|
| English | en |
| 繁體中文 | zh-TW |
| 简体中文 | zh |
| 日本語 | ja |
| 한국어 | ko |
| Français | fr |
| Deutsch | de |
| Español | es |
| Italiano | it |
| Português | pt |
完整支援 55 種語言,詳見 官方文檔
| 模型 | 大小 | 記憶體需求 |
|---|---|---|
| mlx-community/translategemma-4b-it-4bit | ~2GB | ~4GB |
| mlx-community/translategemma-4b-it-8bit | ~4GB | ~6GB |
| mlx-community/translategemma-12b-it-4bit | ~6GB | ~10GB |
| mlx-community/translategemma-27b-it-4bit | ~14GB | ~20GB |
在 Apple Silicon Mac 上的大致效能:
| 機型 | 4B-4bit 翻譯速度 |
|---|---|
| M1 | ~2-3 秒/句 |
| M2 | ~1.5-2 秒/句 |
| M3 | ~1-1.5 秒/句 |
| M4 | ~0.5-1 秒/句 |
升級 mlx-lm:
pip install -U mlx-lm需要先在 Hugging Face 申請存取權限並登入 CLI。
檢查 prompt 格式是否正確,使用 tokenizer.apply_chat_template() 生成 prompt。