中山市建设局安全监督站网站,wordpress图片主题演示,做一个微信商城小程序多少钱,国外性价比高的vpsBaichuan-M2-32B在Linux系统的保姆级部署教程 最近百川智能开源了他们的医疗增强推理模型Baichuan-M2-32B#xff0c;这个模型在医疗领域的表现相当亮眼#xff0c;据说在HealthBench评测集上超越了所有开源模型#xff0c;甚至接近GPT-5的医疗能力。更让人心动的是#x…Baichuan-M2-32B在Linux系统的保姆级部署教程最近百川智能开源了他们的医疗增强推理模型Baichuan-M2-32B这个模型在医疗领域的表现相当亮眼据说在HealthBench评测集上超越了所有开源模型甚至接近GPT-5的医疗能力。更让人心动的是它支持4bit量化这意味着我们可以在单张RTX 4090这样的消费级显卡上就能部署运行。今天我就来手把手教大家如何在Ubuntu 20.04系统上部署Baichuan-M2-32B-GPTQ-Int4版本。整个过程我会尽量讲得详细一些特别是那些容易踩坑的地方确保大家都能顺利跑起来。1. 环境准备与系统检查在开始部署之前我们先要确保系统环境符合要求。Baichuan-M2-32B对硬件和软件都有一定的要求提前检查清楚能避免很多后续问题。1.1 硬件要求首先说说硬件这是最关键的。Baichuan-M2-32B-GPTQ-Int4版本经过4bit量化后显存需求大大降低显卡至少需要24GB显存推荐RTX 409024GB或更高配置内存建议32GB以上64GB更佳存储模型文件大约20GB左右加上其他依赖建议预留50GB空间CPU现代多核处理器即可对CPU要求不高如果你用的是RTX 309024GB或者RTX 4090那完全没问题。如果是其他显卡可以用下面的命令查看显存nvidia-smi --query-gpuname,memory.total --formatcsv1.2 系统要求我们这次以Ubuntu 20.04为例其他Linux发行版也可以参考但命令可能略有不同。先检查一下系统版本lsb_release -a如果显示是Ubuntu 20.04就对了。如果不是也不用太担心大部分步骤都是通用的。1.3 基础依赖安装在安装Python环境之前我们需要先安装一些系统级的依赖库# 更新系统包列表 sudo apt update # 安装基础编译工具和依赖 sudo apt install -y build-essential cmake git wget curl # 安装Python相关依赖 sudo apt install -y python3-pip python3-dev python3-venv # 安装CUDA相关依赖如果使用NVIDIA显卡 sudo apt install -y nvidia-cuda-toolkit # 验证Python版本 python3 --version这里要注意Python版本最好在3.8以上3.10或3.11都是不错的选择。如果系统自带的Python版本太低可以考虑用pyenv来管理多个Python版本。2. Python环境配置为了避免系统Python环境被污染也为了方便管理不同的项目我们使用虚拟环境。这是Python开发中的好习惯。2.1 创建虚拟环境我习惯把虚拟环境放在项目目录里这样管理起来比较方便# 创建一个项目目录 mkdir baichuan-m2-deploy cd baichuan-m2-deploy # 创建Python虚拟环境 python3 -m venv venv # 激活虚拟环境 source venv/bin/activate激活虚拟环境后命令行前面会出现(venv)的提示表示你现在在这个虚拟环境里工作。如果要退出虚拟环境输入deactivate就行。2.2 安装PyTorchPyTorch是深度学习的基础框架我们需要安装与CUDA版本匹配的PyTorch。先查看一下CUDA版本nvcc --version或者用nvidia-smi在右上角可以看到CUDA版本。对于大多数RTX 40系列显卡CUDA 12.1是比较常见的选择。下面是安装命令# 安装PyTorch这里以CUDA 12.1为例 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 # 验证PyTorch是否安装成功并能识别GPU python3 -c import torch; print(fPyTorch版本: {torch.__version__}); print(fCUDA可用: {torch.cuda.is_available()}); print(fGPU数量: {torch.cuda.device_count()})如果看到CUDA可用为TrueGPU数量为1或更多那就说明PyTorch安装成功了。2.3 安装vLLMvLLM是一个高性能的推理引擎专门为大语言模型优化能显著提升推理速度。Baichuan-M2-32B官方推荐使用vLLM来部署# 安装vLLM pip install vllm # 验证vLLM安装 python3 -c import vllm; print(vLLM导入成功)如果安装过程中遇到问题可能是因为缺少一些系统依赖。可以尝试安装开发版本pip install -U vllm --pre --extra-index-url https://wheels.vllm.ai/nightly2.4 安装Transformers和其他依赖Hugging Face的Transformers库是加载和运行模型的基础# 安装Transformers pip install transformers # 安装其他可能需要的依赖 pip install accelerate sentencepiece protobuf # 如果需要从ModelScope下载模型 pip install modelscope3. 模型下载与准备环境准备好了接下来就是下载模型。Baichuan-M2-32B有两个版本原始版本和GPTQ量化版本。我们选择GPTQ-Int4版本因为它对显存要求更低。3.1 从Hugging Face下载模型最直接的方式是从Hugging Face下载。不过模型有20GB左右下载需要一些时间建议找个网络好的环境# 创建一个目录存放模型 mkdir models cd models # 使用git lfs下载模型需要先安装git-lfs sudo apt install -y git-lfs git lfs install git clone https://huggingface.co/baichuan-inc/Baichuan-M2-32B-GPTQ-Int4 # 如果git lfs下载太慢也可以用huggingface-cli pip install huggingface-hub huggingface-cli download baichuan-inc/Baichuan-M2-32B-GPTQ-Int4 --local-dir Baichuan-M2-32B-GPTQ-Int43.2 从ModelScope下载国内推荐如果你在国内从ModelScope下载可能会更快一些# 设置使用ModelScope export VLLM_USE_MODELSCOPETrue # 使用Python代码下载 python3 -c from modelscope import snapshot_download model_dir snapshot_download(baichuan-inc/Baichuan-M2-32B-GPTQ-Int4) print(f模型下载到: {model_dir}) 3.3 验证模型文件下载完成后检查一下模型文件是否完整cd Baichuan-M2-32B-GPTQ-Int4 ls -la你应该能看到这些关键文件config.json模型配置文件model.safetensors或pytorch_model.bin模型权重文件tokenizer.json或相关文件分词器文件special_tokens_map.json特殊token映射4. 使用vLLM部署模型现在到了最关键的一步——用vLLM部署模型。vLLM提供了多种部署方式我们这里介绍两种最常用的命令行启动和Python API启动。4.1 命令行快速启动这是最简单的方式一行命令就能启动一个API服务# 回到项目根目录 cd ../.. # 启动vLLM服务 vllm serve baichuan-inc/Baichuan-M2-32B-GPTQ-Int4 \ --model ./models/Baichuan-M2-32B-GPTQ-Int4 \ --trust-remote-code \ --max-model-len 131072 \ --gpu-memory-utilization 0.9 \ --port 8000让我解释一下这些参数--model指定模型路径可以是本地路径也可以是Hugging Face模型ID--trust-remote-code信任远程代码因为Baichuan-M2使用了自定义的模型代码--max-model-len 131072设置最大上下文长度Baichuan-M2支持128K上下文--gpu-memory-utilization 0.9GPU内存利用率0.9表示使用90%的显存--port 8000服务监听的端口启动成功后你会看到类似这样的输出INFO 07-20 14:30:15 llm_engine.py:197] Initializing an LLM engine with config: ... INFO 07-20 14:30:15 llm_engine.py:398] Loading weights from ./models/Baichuan-M2-32B-GPTQ-Int4 INFO 07-20 14:30:15 model_runner.py:155] Loading model weights took 15.3 GB INFO 07-20 14:30:16 llm_engine.py:491] Model loaded successfully. Uvicorn running on http://0.0.0.0:8000 (Press CTRLC to quit)4.2 Python API启动方式如果你需要在Python程序中控制模型的加载和推理可以用这种方式from vllm import LLM, SamplingParams # 初始化模型 llm LLM( model./models/Baichuan-M2-32B-GPTQ-Int4, trust_remote_codeTrue, max_model_len131072, gpu_memory_utilization0.9 ) # 准备采样参数 sampling_params SamplingParams( temperature0.7, top_p0.9, max_tokens1024 ) # 准备输入 prompts [ Got a big swelling after a bug bite. Need help reducing it., What are the common symptoms of influenza? ] # 生成回复 outputs llm.generate(prompts, sampling_params) # 打印结果 for output in outputs: print(fPrompt: {output.prompt}) print(fGenerated text: {output.outputs[0].text}) print(- * 50)4.3 启动OpenAI兼容的API服务vLLM还提供了OpenAI兼容的API接口这样你就可以用像调用ChatGPT一样的方式调用本地模型# 启动OpenAI兼容的API服务 vllm serve baichuan-inc/Baichuan-M2-32B-GPTQ-Int4 \ --model ./models/Baichuan-M2-32B-GPTQ-Int4 \ --trust-remote-code \ --max-model-len 131072 \ --served-model-name baichuan-m2-32b \ --api-key token-abc123 \ --port 8000启动后你就可以用curl或者Python的openai库来调用了from openai import OpenAI # 初始化客户端 client OpenAI( base_urlhttp://localhost:8000/v1, api_keytoken-abc123 ) # 调用聊天接口 response client.chat.completions.create( modelbaichuan-m2-32b, messages[ {role: system, content: You are a helpful medical assistant.}, {role: user, content: I have a headache and fever, what should I do?} ], temperature0.7, max_tokens1024 ) print(response.choices[0].message.content)5. 模型推理与测试服务启动后我们需要测试一下模型是否正常工作。这里我提供几种测试方法。5.1 简单的文本生成测试先来个最简单的测试看看模型能不能正常生成文本import requests import json # 测试vLLM的generate接口 url http://localhost:8000/generate headers {Content-Type: application/json} data { prompt: What is the capital of France?, max_tokens: 50, temperature: 0.7 } response requests.post(url, headersheaders, datajson.dumps(data)) print(Response:, response.json())5.2 医疗问题测试既然是医疗模型当然要测试一下医疗相关的问题# 测试医疗推理能力 medical_questions [ A patient presents with sudden onset of chest pain radiating to the left arm. What could be the possible causes?, What are the first aid steps for someone having an asthma attack?, How to differentiate between viral and bacterial infections based on symptoms?, What lifestyle changes can help manage type 2 diabetes? ] for question in medical_questions: print(f\nQuestion: {question}) print( * 80) data { prompt: question, max_tokens: 500, temperature: 0.3, # 医疗问题温度设低一些更确定性 top_p: 0.9 } response requests.post(http://localhost:8000/generate, headersheaders, datajson.dumps(data)) if response.status_code 200: result response.json() print(Answer:, result[text][0]) else: print(fError: {response.status_code}) print(- * 80)5.3 思考模式测试Baichuan-M2支持思考模式thinking mode这能让模型先思考再回答适合复杂的推理问题from transformers import AutoTokenizer, AutoModelForCausalLM import torch # 加载模型和分词器 model_path ./models/Baichuan-M2-32B-GPTQ-Int4 tokenizer AutoTokenizer.from_pretrained(model_path, trust_remote_codeTrue) model AutoModelForCausalLM.from_pretrained(model_path, trust_remote_codeTrue, device_mapauto) # 准备输入 prompt A 45-year-old male with history of hypertension presents with severe headache, nausea, and blurred vision. Blood pressure is 210/120 mmHg. What is the most likely diagnosis and what immediate actions should be taken? # 编码输入开启思考模式 messages [{role: user, content: prompt}] text tokenizer.apply_chat_template( messages, tokenizeFalse, add_generation_promptTrue, thinking_modeon # 开启思考模式 ) model_inputs tokenizer([text], return_tensorspt).to(model.device) # 生成回复 generated_ids model.generate( **model_inputs, max_new_tokens1024, temperature0.3 ) # 解析思考内容和最终回答 output_ids generated_ids[0][len(model_inputs.input_ids[0]):].tolist() try: # 查找思考结束的token151668对应/think index len(output_ids) - output_ids[::-1].index(151668) except ValueError: index 0 thinking_content tokenizer.decode(output_ids[:index], skip_special_tokensTrue).strip(\n) content tokenizer.decode(output_ids[index:], skip_special_tokensTrue).strip(\n) print(Thinking process:) print(thinking_content) print(\nFinal answer:) print(content)6. 性能优化与监控部署完成后我们还需要关注模型的性能和资源使用情况。6.1 监控GPU使用情况随时监控GPU状态确保模型运行正常# 实时监控GPU状态 watch -n 1 nvidia-smi # 或者使用更详细的监控 nvidia-smi --query-gputimestamp,name,utilization.gpu,utilization.memory,memory.total,memory.used,memory.free,temperature.gpu --formatcsv -l 16.2 调整vLLM参数优化性能根据你的硬件情况可以调整vLLM的参数来优化性能# 使用张量并行如果有多张GPU vllm serve baichuan-inc/Baichuan-M2-32B-GPTQ-Int4 \ --model ./models/Baichuan-M2-32B-GPTQ-Int4 \ --trust-remote-code \ --tensor-parallel-size 2 \ # 使用2张GPU --max-model-len 131072 \ --gpu-memory-utilization 0.85 \ --max-num-batched-tokens 4096 \ # 增加批处理token数 --port 8000 # 使用paged attention优化内存 vllm serve baichuan-inc/Baichuan-M2-32B-GPTQ-Int4 \ --model ./models/Baichuan-M2-32B-GPTQ-Int4 \ --trust-remote-code \ --max-model-len 131072 \ --enable-prefix-caching \ # 启用前缀缓存 --block-size 16 \ # 调整块大小 --port 80006.3 批量处理优化如果需要处理大量请求可以启用批量处理from vllm import LLM, SamplingParams llm LLM( model./models/Baichuan-M2-32B-GPTQ-Int4, trust_remote_codeTrue, max_model_len131072, enable_prefix_cachingTrue, # 启用前缀缓存 max_num_batched_tokens4096, # 增加批处理token数 max_num_seqs256 # 增加同时处理的序列数 ) # 批量处理请求 sampling_params SamplingParams(temperature0.7, max_tokens512) prompts [fMedical question {i}: What are the symptoms of condition X? for i in range(10)] outputs llm.generate(prompts, sampling_params) for output in outputs: print(fGenerated: {output.outputs[0].text[:100]}...)7. 常见问题与解决方案在部署过程中你可能会遇到一些问题。这里我整理了一些常见问题和解决方法。7.1 显存不足问题问题启动时出现CUDA out of memory错误。解决方案降低--gpu-memory-utilization参数比如从0.9降到0.8使用更小的批处理大小--max-num-batched-tokens 2048确保没有其他程序占用GPU显存如果只有一张24GB显卡确保模型是GPTQ-Int4版本# 调整后的启动命令 vllm serve baichuan-inc/Baichuan-M2-32B-GPTQ-Int4 \ --model ./models/Baichuan-M2-32B-GPTQ-Int4 \ --trust-remote-code \ --max-model-len 65536 \ # 降低上下文长度 --gpu-memory-utilization 0.8 \ --max-num-batched-tokens 2048 \ --port 80007.2 模型加载失败问题加载模型时出现错误特别是trust_remote_code相关错误。解决方案确保安装了所有依赖pip install transformers accelerate检查模型文件是否完整下载尝试从ModelScope下载而不是Hugging Face# 设置使用ModelScope export VLLM_USE_MODELSCOPETrue # 重新启动 vllm serve baichuan-inc/Baichuan-M2-32B-GPTQ-Int4 \ --trust-remote-code \ --port 80007.3 推理速度慢问题模型推理速度比预期慢。解决方案检查GPU是否在高效运行状态增加批处理大小--max-num-batched-tokens 8192使用更快的注意力实现如果支持确保使用GPTQ量化版本而不是原始版本# 优化后的启动命令 vllm serve baichuan-inc/Baichuan-M2-32B-GPTQ-Int4 \ --model ./models/Baichuan-M2-32B-GPTQ-Int4 \ --trust-remote-code \ --max-num-batched-tokens 8192 \ --block-size 32 \ --enable-prefix-caching \ --port 80007.4 API服务无法访问问题服务启动成功但无法从外部访问。解决方案检查防火墙设置sudo ufw allow 8000绑定到0.0.0.0而不是127.0.0.1检查端口是否被占用sudo lsof -i :8000# 明确绑定到所有接口 vllm serve baichuan-inc/Baichuan-M2-32B-GPTQ-Int4 \ --model ./models/Baichuan-M2-32B-GPTQ-Int4 \ --trust-remote-code \ --host 0.0.0.0 \ # 绑定到所有网络接口 --port 80008. 实际应用示例最后我们来看几个实际的应用示例展示Baichuan-M2-32B能做什么。8.1 医疗问答系统你可以基于这个模型搭建一个简单的医疗问答系统from flask import Flask, request, jsonify from vllm import LLM, SamplingParams import threading app Flask(__name__) # 全局模型实例 llm None sampling_params SamplingParams(temperature0.3, max_tokens512) def init_model(): global llm llm LLM( model./models/Baichuan-M2-32B-GPTQ-Int4, trust_remote_codeTrue, max_model_len65536, gpu_memory_utilization0.85 ) app.route(/ask, methods[POST]) def ask_medical_question(): data request.json question data.get(question, ) if not question: return jsonify({error: No question provided}), 400 # 添加系统提示 full_prompt fYou are a professional medical assistant. Please provide helpful, accurate, and safe medical information. Question: {question} Please provide a clear, concise answer based on medical knowledge. If the question requires immediate medical attention, state that clearly. Answer: # 生成回答 outputs llm.generate([full_prompt], sampling_params) answer outputs[0].outputs[0].text return jsonify({ question: question, answer: answer }) if __name__ __main__: # 在后台初始化模型 init_thread threading.Thread(targetinit_model) init_thread.start() init_thread.join() print(Model loaded, starting Flask server...) app.run(host0.0.0.0, port5000, threadedTrue)8.2 病历分析与总结模型还可以用于分析病历文本def analyze_medical_record(record_text): prompt fAnalyze the following medical record and provide a summary: Medical Record: {record_text} Please provide: 1. Key symptoms and findings 2. Possible diagnoses (list in order of likelihood) 3. Recommended tests or referrals 4. Immediate actions if urgent Analysis: outputs llm.generate([prompt], sampling_params) return outputs[0].outputs[0].text # 示例病历 sample_record Patient: 58-year-old female Chief Complaint: Shortness of breath and chest discomfort for 2 days History: Hypertension for 10 years, type 2 diabetes for 5 years Examination: BP 150/95, HR 110 bpm, RR 22/min, SpO2 92% on room air ECG: Sinus tachycardia, no acute ST changes Labs: Troponin slightly elevated at 0.05 ng/mL analysis analyze_medical_record(sample_record) print(Medical Record Analysis:) print(analysis)8.3 药物信息查询构建一个药物信息查询工具def get_drug_information(drug_name): prompt fProvide comprehensive information about the drug: {drug_name} Please include: 1. Drug class and mechanism of action 2. Common indications (what its used for) 3. Standard dosage (adult) 4. Common side effects 5. Important contraindications and warnings 6. Major drug interactions Information should be based on standard medical references. outputs llm.generate([prompt], sampling_params) return outputs[0].outputs[0].text # 查询常见药物信息 drugs [Metformin, Lisinopril, Atorvastatin, Warfarin] for drug in drugs: print(f\n{*60}) print(fDrug Information: {drug}) print(*60) info get_drug_information(drug) print(info[:500] ... if len(info) 500 else info)9. 总结走完这一整套流程你应该已经在Ubuntu系统上成功部署了Baichuan-M2-32B-GPTQ-Int4模型。整个过程从环境准备到模型测试我尽量把每个步骤都讲清楚特别是那些容易出问题的地方。实际用下来这个模型的医疗推理能力确实不错回答比较专业而且因为做了4bit量化在消费级显卡上就能跑起来这对很多个人开发者和小团队来说是个好消息。部署过程虽然有些步骤但跟着教程一步步来基本上都能搞定。如果你在部署过程中遇到其他问题或者想尝试不同的配置可以多看看官方文档和社区讨论。每个硬件环境可能都有些差异需要适当调整参数。比如显存大小、批处理尺寸这些都要根据实际情况来调。最后提醒一下虽然这个模型在医疗领域表现很好但它不能替代专业医生的诊断。在实际应用中要谨慎使用特别是涉及具体医疗建议时一定要有专业人士的审核。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。