WSL 极速部署 llama.cpp:三步搞定 CPU、GPU 本地运行大模型(CUDA 加速)
摘要想在 Windows 下本地跑大模型又不想搞双系统WSL llama.cpp是最轻量、高效的选择。本文将带你一步步完成环境配置、源码编译可选 NVIDIA GPU 加速并下载模型直接运行。无需复杂依赖CPU 可跑CUDA 更快真正实现“开箱即用”的本地 LLM 体验。在 WSL 中安装llama.cpp主要分为环境准备、源码编译和模型下载三步。如果你想用英伟达显卡加速编译时需要开启 CUDA 支持。 准备工作在开始前请确保满足以下条件WSL2 环境建议使用 Ubuntu 22.04 或 20.04。在 Windows PowerShell 中运行wsl --set-version 你的发行版名 2可确认版本。基础依赖更新软件源并安装编译工具sudoaptupdatesudoaptupgrade-ysudoaptinstall-ybuild-essential cmakegitwgetpython3-pip可选NVIDIA 显卡驱动如果使用 GPUWindows 端需安装支持 WSL2 的 NVIDIA 驱动版本 ≥ 535。⚙️ 安装步骤1. 克隆仓库并编译首先下载源码然后根据是否使用 GPU 选择编译命令。# 1. 克隆项目gitclone https://github.com/ggerganov/llama.cppcdllama.cpp# 2. 创建编译文件夹mkdirbuildcdbuildGPU 版本NVIDIA 显卡推荐首先需要在 WSL 内安装 CUDA 工具包# 添加 NVIDIA 仓库并安装 CUDA 12.9wgethttps://developer.download.nvidia.com/compute/cuda/repos/wsl-ubuntu/x86_64/cuda-keyring_1.1-1_all.debsudodpkg-icuda-keyring_1.1-1_all.debsudoapt-getupdatesudoapt-get-yinstallcuda-toolkit-12-6编译时开启 CUDA 支持# 设置环境变量exportPATH/usr/local/cuda/bin:$PATHexportLD_LIBRARY_PATH/usr/local/cuda/lib64:$LD_LIBRARY_PATH# 编译cmake..-DGGML_CUDAON cmake--build.--configRelease-j$(nproc)2. 安装 anacondabashMiniconda3-latest-Linux-x86_64.sh# 安装完 anacondasource 环境source~/.bashrc# 初始化conda init# 查看 conda 版本conda--version# 配置清华源pip configsetglobal.index-url https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple pip config list3. 下载模型文件llama.cpp需要特定格式GGUF的模型文件。可以从 Hugging Face 或 modelscope 下载# 安装 huggingface-hub方便下载国外模型pipinstallhuggingface-hub# 安装 modelscope 方便下载国内模型pipinstallmodelscope# 下载模型以 Qwen2-0.5B 为例文件很小适合测试huggingface-cli download Qwen/Qwen2-0.5B-Instruct-GGUF --local-dir ./models--includeq4_0.ggufmodelscope download--modelTencent-Hunyuan/HY-MT1.5-7B-GGUF HY-MT1.5-7B-Q6_K.gguf License.txt configuration.json README.md--local_dir./HY-MT1.5-7B-Q6_K4. 运行与验证编译完成后在build/bin目录下可以看到main推理和llama-cli等可执行文件。使用以下命令运行一个测试对话# -m: 指定模型路径 model directory# -p: 输入的提示词 prompt# -n: 生成的最大token数 predict max tokens# -c: 设定上下文窗口 context length# --chat-template-file 后端启动Qwen 带思考的模型时关闭思考模式不添加这个参数默认支持思考模式# -ngl 将模型的多少层加载到GPU中假如模型 40层-ngl 20 设置成 20那么 GPU 加载 20层剩余层加载到 CPU 中Number of GPU Layers# Qwen3.6-35B-A3B-UD-Q3_K_XL./llama-cli\-m/mnt/d/models/Qwen3.6-35B-A3B-UD-Q3_K_XL/Qwen3.6-35B-A3B-UD-Q3_K_XL.gguf\-c8192\-n512\-p你好请用中文自我介绍\--temp0.7\--jinja\--chat-template-file /mnt/d/models/qwen3_nonthinking.jinja# Qwen3.6-35B-A3B-UD-Q3_K_XL./llama-server\-m/mnt/d/models/Qwen3.6-35B-A3B-UD-Q3_K_XL/Qwen3.6-35B-A3B-UD-Q3_K_XL.gguf\-c8192\-ngl99\--host0.0.0.0\--port8080\--cache-type-k q8_0\--cache-type-v q8_0\--temp0.7\--jinja\--chat-template-file /mnt/d/models/qwen3_nonthinking.jinja# 查看显存情况和CUDA 驱动版本nvidia-smi# 实时查看显存情况watch-n1nvidia-smi# 查看运行时 CUDA 版本 如果安装了 CUDA toolkitnvcc--version# 安装 cuda toolkitsudoaptinstallnvidia-cuda-toolkit5. 用测试脚本测试# 创建 conda python 虚拟环境conda create-nlangchain_1.0python3.12-y# 安装 openaipipinstallopenai测试脚本importosimporttimefromopenaiimportOpenAI# from get_system_prompt import get_system_prompt# 初始化 OpenAI 客户端指向本地 llama-serverclientOpenAI(base_urlhttp://localhost:8080/v1,api_keysk-no-key-required# 本地服务不需要真实 API Key)# 获取系统提示词# system_prompt get_system_prompt()system_prompt你是一个乐于助人的智能助手# 创建对话历史存储messages[{role:system,content:system_prompt}]# Token 估算函数简化版中文约 1.5 字符/token英文约 4 字符/tokendefestimate_tokens(text):ifnottext:return0# 简单估算假设平均每个 token 约 2 个字符中英文混合returnint(len(text)/2)print(*50)print( AI 助手已启动输入 退出 结束对话)print(*50)# 对话循环turn_count0# 对话轮数计数器whileTrue:# 获取用户输入user_inputinput(\n 用户: ).strip()# 检查退出条件ifuser_input.lower()in[退出,exit,quit,q]:print(\n 感谢使用再见)breakifnotuser_input:continue# 增加轮数turn_count1# 添加用户消息到历史messages.append({role:user,content:user_input})print(\n AI: ,end,flushTrue)try:# 记录请求开始时间start_timetime.perf_counter()first_token_timeNone# 创建流式输出请求streamclient.chat.completions.create(modelqwen3-8b,messagesmessages,streamTrue,temperature0.7)# 流式接收并打印响应full_responseforchunkinstream:ifchunk.choicesandchunk.choices[0].delta.content:contentchunk.choices[0].delta.contentprint(content,end,flushTrue)full_responsecontent# 记录首 token 时间iffirst_token_timeisNone:first_token_timetime.perf_counter()# 记录结束时间end_timetime.perf_counter()print()# 换行# 计算统计指标ttft(first_token_time-start_time)*1000iffirst_token_timeelse0total_time(end_time-start_time)*1000generation_time(end_time-first_token_time)*1000iffirst_token_timeelse0# 估算 token 数current_turn_tokensestimate_tokens(full_response)system_prompt_tokensestimate_tokens(system_prompt)total_context_tokensestimate_tokens(\n.join([m[content]forminmessages]))tokens_per_second(current_turn_tokens/generation_time*1000)ifgeneration_time0else0# 打印统计信息print(\n-*50)print(f 性能统计 (第{turn_count}轮对话):)print(f ⏱️ TTFT (首字节延迟):{ttft:.2f}ms)print(f ⏱️ 总耗时:{total_time:.2f}ms)print(f ⏱️ 生成耗时:{generation_time:.2f}ms)print(f 本轮生成 Tokens:{current_turn_tokens})print(f 生成速度:{tokens_per_second:.2f}tokens/s)print(f 系统提示词 Tokens:{system_prompt_tokens})print(f 上下文总 Tokens:{total_context_tokens})print(-*50)# 添加 AI 回复到历史messages.append({role:assistant,content:full_response})# 控制历史长度保留 system 最近 10 轮对话iflen(messages)21:messages[messages[0]]messages[-20:]turn_count10# 重置轮数显示因为只保留最近10轮exceptExceptionase:print(f\n❌ 发生错误:{e})importtraceback traceback.print_exc()continue运行测试脚本python test_openai.py备注./llama-server 启动服务接口通过端口来指定模型与传递的模型参数无关可以通过不同端口启动多个./llama-server服务GPU 优化运行 GPU 版本时建议增加--n-gpu-layers参数如-ngl 99来将更多计算层加载到显存中从而显著提升速度。性能监控在 WSL 终端输入nvidia-smi可以实时查看 GPU 的显存占用和使用率。 常见问题编译报错nvcc not found通常是 CUDA 环境变量未生效重新运行export PATH...命令或重启终端即可。显存不足 (OOM)可以尝试减少--n-gpu-layers的数量或者选择更小的模型及更低的量化版本如从 Q4 换成 Q2。中文乱码可能是终端编码问题运行export LANGzh_CN.UTF-8临时设置一下。整个流程走下来如果遇到具体的报错欢迎随时告诉我。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2535507.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!