Mac m1 本地运行 deepseek-r1-distill-qwen-1.5B
·
Mac m1 本地运行 deepseek-r1-distill-qwen-1.5B
1、安装Homebrew(使用国内镜像源)
1、创建缺失的目录结构
# 创建必要的目录
sudo mkdir -p /opt/homebrew/Library/Taps/homebrew
sudo chown -R $(whoami) /opt/homebrew/Library/Taps
2、手动克隆核心仓库(使用国内镜像源)
# 进入目标目录
cd /opt/homebrew/Library/Taps/homebrew
# 从镜像源克隆仓库
git clone https://mirrors.ustc.edu.cn/homebrew-core.git
# 重命名目录为规范名称
mv homebrew-core homebrew-core-orig
mv homebrew-core-orig homebrew-core
3、重新链接仓库
# 设置远程源
git -C "/opt/homebrew/Library/Taps/homebrew/homebrew-core" remote set-url origin https://mirrors.ustc.edu.cn/homebrew-core.git
# 验证链接
git -C "/opt/homebrew/Library/Taps/homebrew/homebrew-core" remote -v
# 应显示:
# origin https://mirrors.ustc.edu.cn/homebrew-core.git (fetch)
# origin https://mirrors.ustc.edu.cn/homebrew-core.git (push)
4、完成 Homebrew 初始化
# 更新仓库
brew update --force
# 修复权限
sudo chown -R $(whoami) /opt/homebrew/*
5、添加环境变量加速
# 添加环境变量加速
export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.ustc.edu.cn/homebrew-bottles
2、安装python
1、使用 Homebrew 安装
Homebrew 是 macOS 上常用的包管理工具,可以方便地安装和管理 Python。
安装 Homebrew(如果尚未安装)
- 打开终端,运行以下命令:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
安装 Python
- 在终端中运行以下命令:
brew install python
验证安装
- 安装完成后,运行以下命令检查 Python 版本:
python3 --version
2、设置环境变量
- 如果需要将 Homebrew 安装的 Python 设为默认版本,可以将以下内容添加到 ~/.zshrc 或 ~/.bashrc 文件中:
确认当前使用的 Shell
在终端中运行以下命令,查看当前 Shell 类型:
echo $SHELL
- 如果输出 /bin/zsh:说明你使用的是 zsh,但缺少 .zshrc 文件。
- 如果输出 /bin/bash:说明你使用的是 bash,应修改 .bash_profile 或 .bashrc。
根据 Shell 类型操作
情况 1:使用 zsh(输出为 /bin/zsh)
1.创建 .zshrc 文件:
touch ~/.zshrc
2.添加环境变量到 .zshrc:
echo 'export PATH="/usr/local/opt/python/libexec/bin:$PATH"' >> ~/.zshrc
3.使配置生效:
source ~/.zshrc
情况 2:使用 bash(输出为 /bin/bash)
1.修改 .bash_profile 或 .bashrc:
echo 'export PATH="/usr/local/opt/python/libexec/bin:$PATH"' >> ~/.bash_profile
2.使配置生效:
source ~/.bash_profile
验证路径是否生效
运行以下命令,检查路径是否包含 Python 的安装路径:
echo $PATH
- 输出中应包含 /usr/local/opt/python/libexec/bin。
3、使用 pyenv 管理多个 Python 版本
pyenv 是一个 Python 版本管理工具,可以方便地切换不同版本的 Python。
安装 pyenv
- 使用 Homebrew 安装 pyenv:
brew install pyenv
安装 Python
- 使用 pyenv 安装指定版本的 Python:
pyenv install 3.x.x
设置全局 Python 版本(不推荐)
- 为什么 macOS 不推荐使用 python 命令:macOS 系统依赖 Python 2 运行部分系统工具,直接修改系统级 Python 可能导致不稳定。建议通过 python3 或虚拟环境管理项目。
- 将安装的 Python 版本设为全局默认
pyenv global 3.x.x
验证安装
- 运行以下命令检查 Python 版本:
python --version
3、安装依赖
1、使用虚拟环境(推荐)
为避免依赖冲突,建议创建并激活虚拟环境:
# 安装虚拟环境工具(若未安装)
pip3 install virtualenv
# 创建虚拟环境
python3 -m venv deepseek-env
# 激活虚拟环境
source deepseek-env/bin/activate
# ========== ↓↓↓ 安装依赖 ↓↓↓ ==========
# 在虚拟环境中安装依赖
# pip install tqdm numpy torch
# ========== ↑↑↑ 安装依赖 ↑↑↑ ==========
# 退出虚拟环境
deactivate
关键检查点
1.确认 Python 和 pip 版本:
python3 --version # 应为 Python 3.6+
pip3 --version # 应指向与 python3 匹配的路径
2、安装 tqdm
# 确保使用 Python 3 对应的 pip
pip3 install tqdm
# 如果提示权限不足,尝试以下命令之一:
pip3 install --user tqdm # 安装到用户目录
sudo pip3 install tqdm # 全局安装(需 root 权限)
验证安装
python3 -c "import tqdm; print('tqdm 已安装')"
- 若输出 tqdm 已安装 则表明安装成功。
3、安装torch
对于 Apple Silicon 芯片,PyTorch 官方推荐使用以下命令安装:
pip install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu
验证安装
# 进入python3环境
python3
import torch
print(torch.__version__) # 应该显示 2.x 版本
print(torch.backends.mps.is_available()) # 应该返回 True,检查 M1/M2 GPU 加速是否可用
# 退出Python环境
exit()
4、安装模型依赖
成功安装 PyTorch 后,继续安装其他依赖:
pip install transformers accelerate sentencepiece
4、安装编译环境
1、确认依赖库安装状态
# 在激活的虚拟环境中执行(确保终端提示符前有 (deepseek-env))
pip list | grep -E "transformers|sentencepiece|accelerate"
- 若输出为空或缺少任一库,需重新安装。
2、优先安装编译工具链
# 强制使用二进制包安装
brew install --force-bottle cmake pkg-config coreutils
# 安装必备工具
# brew install cmake pkg-config coreutils
# 将 coreutils 加入 PATH(针对 zsh)
echo 'export PATH="/opt/homebrew/opt/coreutils/libexec/gnubin:$PATH"' >> ~/.zshrc
source ~/.zshrc
验证安装
# 检查工具链
cmake --version # 应显示 ≥3.29
pkg-config --version # 应显示 ≥0.29
nproc # 应返回 CPU 核心数
3、安装 sentencepiece
# 方法一:使用 conda 规避编译问题(推荐)
# conda install -c conda-forge sentencepiece
# 方法二:通过 pip 安装(需确保已安装上述编译工具)
pip install --no-cache-dir sentencepiece
4、安装其他依赖
pip install transformers accelerate
验证关键库安装
# 在 Python 交互环境中逐条执行
import transformers
print(transformers.__version__) # 应输出 4.40.0+
import sentencepiece
print(sentencepiece.__version__) # 应输出 0.2.0+
import torch
print(torch.backends.mps.is_available()) # 应返回 True
5、修正模型加载代码
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch # 需显式导入 torch
model_name = "deepseek-ai/deepseek-r1-distill-qwen-1.5B"
# 加载 Tokenizer
tokenizer = AutoTokenizer.from_pretrained(
model_name,
trust_remote_code=True
)
# 加载模型(优化后的参数配置)
model = AutoModelForCausalLM.from_pretrained(
model_name,
device_map="auto",
torch_dtype=torch.float16,
trust_remote_code=True
).to('mps') # 显式指定 MPS 设备
# 验证模型运行
input_text = "DeepSeek-R1 是一款"
inputs = tokenizer(input_text, return_tensors="pt").to('mps')
outputs = model.generate(**inputs, max_length=50)
print(tokenizer.decode(outputs[0]))
5、内存优化
解决方案 (4 种方式任选其一)
1、方案 1:禁用自动卸载功能
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
model_name = "deepseek-ai/deepseek-r1-distill-qwen-1.5B"
# 加载 Tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
# 加载模型时禁用自动卸载
model = AutoModelForCausalLM.from_pretrained(
model_name,
device_map="auto", # 保持自动分配
torch_dtype=torch.float16, # 半精度
trust_remote_code=True,
offload_folder=None, # 禁止卸载到磁盘
offload_state_dict=False # 禁止状态字典卸载
).to('mps') # 现在可以安全移动
print(next(model.parameters()).device) # 应显示 mps
2、方案 2:直接使用自动设备分配 (推荐)
model = AutoModelForCausalLM.from_pretrained(
model_name,
device_map="auto", # 自动选择最优设备 (优先 MPS)
torch_dtype=torch.float16,
trust_remote_code=True
)
# 不需要手动 .to("mps")
# 验证设备
print(model.device) # 应显示 mps:0
3、方案 3:强制指定 MPS 设备映射
model = AutoModelForCausalLM.from_pretrained(
model_name,
device_map={"": "mps"}, # 强制主设备为 MPS
torch_dtype=torch.float16,
trust_remote_code=True
)
4、方案 4:优化内存配置
model = AutoModelForCausalLM.from_pretrained(
model_name,
device_map="auto",
torch_dtype=torch.bfloat16, # 改用内存更友好的 bfloat16
low_cpu_mem_usage=True, # 优化内存使用
trust_remote_code=True
)
5、验证模型运行
input_text = "DeepSeek-R1 是一款"
inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
# 生成文本
outputs = model.generate(
**inputs,
max_new_tokens=100,
do_sample=True,
temperature=0.7
)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
关键参数说明
| 参数 | 说明 | 推荐值 |
|---|---|---|
| device_map | 设备分配策略 | “auto” 或 {“”: “mps”} |
| torch_dtype | 张量精度 | torch.float16 / torch.bfloat16 |
| offload_folder | 磁盘卸载路径 | None (禁用卸载) |
| low_cpu_mem_usage | 内存优化 | True |
6、模型示例
在本地使用 deepseek-r1-distill-qwen-1.5B 模型,通常需要以下步骤。以下是详细的配置指南和示例代码:
1、环境准备
硬件要求
-
最低配置(CPU 推理):
-
CPU:4 核以上(推荐 Intel i5/i7 或 AMD Ryzen 5/7)
-
内存:16GB+(模型越小需求越低)
-
存储:20GB+ 可用空间(用于模型文件和依赖)
-
推荐配置(GPU 加速):
-
GPU:NVIDIA RTX 3060 及以上(显存 ≥ 8GB)
-
CUDA 版本:≥ 11.8
-
内存:32GB+
2、加载模型与分词器
假设模型已发布在 HuggingFace Hub(如 deepseek-ai/deepseek-r1-distill-qwen-1.5B),直接通过以下代码加载:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "deepseek-ai/deepseek-r1-distill-qwen-1.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_name,
device_map="auto", # 自动分配设备(优先使用 MPS GPU)
torch_dtype=torch.float16, # 半精度减少显存占用
trust_remote_code=True # 信任自定义代码(如 Qwen 架构)
).to("mps") # 显式指定 MPS 设备
3、运行推理
1. 基础文本生成
input_text = "中国的首都是哪里?"
inputs = tokenizer(input_text, return_tensors="pt").to("mps") # 输入数据转移到 MPS 设备
outputs = model.generate(
**inputs,
max_new_tokens=100, # 生成最大长度
temperature=0.7, # 控制随机性(0~1,值越大越随机)
do_sample=True
)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
2. 流式输出(逐句生成)
from transformers import TextStreamer
streamer = TextStreamer(tokenizer)
inputs = tokenizer([input_text], return_tensors="pt").to("mps")
model.generate(**inputs, streamer=streamer, max_new_tokens=200)
4、性能优化
1、4-bit 量化(减少显存占用)
pip install bitsandbytes # 安装量化依赖
from transformers import BitsAndBytesConfig
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16
)
model = AutoModelForCausalLM.from_pretrained(
model_name,
quantization_config=bnb_config,
device_map="auto",
trust_remote_code=True
)
2、使用 llama.cpp 加速(CPU 优化)
如果 GPU 显存不足,可将模型转换为 GGUF 格式并用 CPU 推理:
# 安装 llama.cpp
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp && make
# 转换模型为 GGUF 格式(需先下载 PyTor 格式的模型)
python3 convert.py ./model --outfile ./model-q4.gguf --q4
# 运行推理
./main -m model-q4.gguf -p "你的输入" -n 512 -t 6 # -t 为线程数
3、使用 MLX(Apple 专用框架)
通过苹果官方 MLX 框架进一步优化性能:
pip install mlx
from mlx.utils import tree_unflatten
import mlx.core as mx
# 将 PyTorch 模型权重转换为 MLX 格式
weights = {k: mx.array(v.cpu().numpy()) for k, v in model.state_dict().items()}
model = tree_unflatten(list(weights.items()))
5、完整示例代码
from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer
import torch
# 加载模型和分词器
model_name = "deepseek-ai/deepseek-r1-distill-qwen-1.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_name,
device_map="auto",
torch_dtype=torch.float16,
trust_remote_code=True
).to("mps")
# 流式生成
input_text = "如何做西红柿炒鸡蛋?"
streamer = TextStreamer(tokenizer)
inputs = tokenizer(input_text, return_tensors="pt").to("mps")
model.generate(
**inputs,
max_new_tokens=200,
temperature=0.7,
streamer=streamer
)
更多推荐




所有评论(0)