Llama 3.1 本地部署与 API 服务搭建
一、环境准备
部署服务器: H100 80G 模型: Llama-3.1-8B-Instruct
1. 创建 Conda 虚拟环境
建议使用 Python 3.10 以上版本。
conda create -n llama3 python=3.11
2. 激活环境
conda activate llama3
3. 安装 PyTorch
查看 CUDA 版本:
nvidia-smi
根据 CUDA 版本选择适合的 PyTorch 版本(建议选择不大于主机支持的最高版本),使用镜像源安装:
pip install torch==2.6.0 torchvision==0.21.0 torchaudio==2.6.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
4. 升级 Pip 及工具
python -m pip install --upgrade pip
wget --version
md5sum --version
若缺少 wget 或 md5sum,可执行:
apt-get install wget
apt-get install md5sum
5. 安装依赖库
pip install --upgrade transformers
pip install accelerate -i https://pypi.tuna.tsinghua.edu.cn/simple
二、本地部署模型测试
从 HuggingFace 下载模型:https://huggingface.co/meta-llama/Llama-3.1-8B
代码示例
import transformers
import torch
model_id = "meta-llama/Meta-Llama-3.1-8B-Instruct"
pipeline = transformers.pipeline(
"text-generation",
model=model_id,
model_kwargs={"torch_dtype": torch.bfloat16},
device_map="auto"
)
messages = [
{"role": "system", "content": "You are a pirate chatbot who always responds in pirate speak!"},
{"role": "user", "content": }
]
outputs = pipeline(messages, max_new_tokens=)
(outputs[][][-])

