GLM-4-9B-Chat-1M部署详解:vLLM engine_args配置、tokenizer_path指定、chat_template注入

发布时间:2026/6/24 7:09:53

GLM-4-9B-Chat-1M部署详解:vLLM engine_args配置、tokenizer_path指定、chat_template注入 GLM-4-9B-Chat-1M部署详解vLLM engine_args配置、tokenizer_path指定、chat_template注入想体验支持100万上下文长度的开源大模型吗GLM-4-9B-Chat-1M就是这样一个让人兴奋的选择。它能处理约200万中文字符的超长文本在多语言对话、代码执行、工具调用等方面都有出色表现。但这么强大的模型部署起来会不会很复杂特别是当你需要用到vLLM这样的高性能推理引擎时各种配置参数让人眼花缭乱。engine_args该怎么设置tokenizer_path如何指定chat_template又该怎么注入别担心这篇文章就是为你准备的。我会手把手带你完成GLM-4-9B-Chat-1M的完整部署流程重点讲解那些容易踩坑的配置细节。无论你是想快速搭建一个可用的服务还是想深入了解vLLM的配置原理都能在这里找到答案。1. 环境准备与快速部署1.1 系统要求与依赖安装在开始之前确保你的系统满足以下基本要求操作系统Ubuntu 20.04或更高版本其他Linux发行版也可但本文以Ubuntu为例Python版本Python 3.8-3.11GPU内存至少24GB显存FP16精度系统内存至少32GB RAM磁盘空间至少50GB可用空间首先安装必要的系统依赖# 更新系统包 sudo apt update sudo apt upgrade -y # 安装Python开发工具 sudo apt install -y python3-pip python3-dev python3-venv # 安装CUDA工具包如果尚未安装 # 这里以CUDA 12.1为例根据你的GPU驱动选择合适版本 wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-keyring_1.1-1_all.deb sudo dpkg -i cuda-keyring_1.1-1_all.deb sudo apt update sudo apt install -y cuda-toolkit-12-11.2 创建Python虚拟环境为了避免依赖冲突建议使用虚拟环境# 创建虚拟环境 python3 -m venv glm4_env # 激活虚拟环境 source glm4_env/bin/activate # 升级pip pip install --upgrade pip1.3 安装vLLM和必要库vLLM是当前最流行的高性能大模型推理引擎之一特别适合部署像GLM-4-9B-Chat-1M这样的大模型# 安装vLLM包含PyTorch等依赖 pip install vllm # 安装模型相关的额外依赖 pip install transformers4.36.0 pip install sentencepiece # GLM分词器需要 pip install protobuf # 安装Web框架用于API服务 pip install fastapi uvicorn # 安装chainlit用于Web界面 pip install chainlit安装完成后可以验证vLLM是否正确安装python -c import vllm; print(fvLLM版本: {vllm.__version__})如果看到版本号输出说明安装成功。2. 模型下载与配置详解2.1 下载GLM-4-9B-Chat-1M模型GLM-4-9B-Chat-1M模型可以从Hugging Face或ModelScope获取。这里以Hugging Face为例# 安装huggingface-hub pip install huggingface-hub # 下载模型需要先登录Hugging Face # 如果没有账号可以先跳过登录部分模型可能无法下载 huggingface-cli login # 下载模型到本地 python -c from huggingface_hub import snapshot_download model_id THUDM/glm-4-9b-chat-1m local_dir ./glm-4-9b-chat-1m snapshot_download( repo_idmodel_id, local_dirlocal_dir, local_dir_use_symlinksFalse, resume_downloadTrue ) print(f模型已下载到: {local_dir}) 如果网络条件不好也可以使用镜像源或者先下载到本地再传输。2.2 理解模型文件结构下载完成后查看模型目录结构tree -L 2 ./glm-4-9b-chat-1m/你会看到类似这样的结构glm-4-9b-chat-1m/ ├── config.json ├── generation_config.json ├── model.safetensors ├── tokenizer.json ├── tokenizer_config.json ├── special_tokens_map.json └── ...关键文件说明config.json模型配置文件包含模型架构、参数等信息model.safetensors模型权重文件safetensors格式更安全tokenizer.json分词器配置文件tokenizer_config.json分词器额外配置3. vLLM engine_args配置详解3.1 基础engine_args配置vLLM的核心是LLM类通过engine_args参数控制推理引擎的行为。下面是一个基础的配置示例from vllm import LLM, SamplingParams # 基础配置 llm LLM( model./glm-4-9b-chat-1m, # 模型路径 tensor_parallel_size1, # 张量并行度单GPU设为1 gpu_memory_utilization0.9, # GPU内存利用率0.9表示使用90%显存 max_num_seqs256, # 最大并发序列数 max_model_len1048576, # 最大模型长度1M上下文 trust_remote_codeTrue, # 信任远程代码GLM需要 dtypehalf, # 半精度浮点数节省显存 seed42, # 随机种子保证可重复性 ) print(vLLM引擎初始化完成)3.2 关键参数解析让我详细解释几个重要的engine_args参数1. tensor_parallel_size这个参数控制张量并行度。如果你有多个GPU可以设置为GPU数量来加速推理。比如有4张GPU就设为4。2. gpu_memory_utilizationGPU内存利用率范围0-1。设为0.9意味着vLLM会尝试使用90%的可用显存。设置太高可能导致OOM内存不足太低则浪费显存。3. max_model_len这是GLM-4-9B-Chat-1M的关键参数必须设置为10485761M。如果设置小了就无法发挥模型的长上下文优势。4. trust_remote_codeGLM模型需要加载自定义的模型代码所以必须设为True。如果设为FalsevLLM会拒绝加载模型。3.3 高级优化配置对于生产环境你可能需要更精细的配置from vllm import LLM # 高级配置示例 llm LLM( model./glm-4-9b-chat-1m, tensor_parallel_size1, pipeline_parallel_size1, # 流水线并行度 block_size16, # KV缓存块大小 swap_space4, # CPU交换空间GB max_num_batched_tokens2048, # 最大批处理token数 max_num_seqs256, max_model_len1048576, trust_remote_codeTrue, dtypehalf, enforce_eagerTrue, # 强制使用eager模式兼容性更好 kv_cache_dtypeauto, # KV缓存数据类型 quantizationNone, # 量化方式如awq、gptq seed42, ) print(高级配置vLLM引擎初始化完成)配置建议如果遇到内存不足可以尝试降低gpu_memory_utilization或启用swap_space对于对话场景max_num_seqs可以设大一些支持更多并发block_size影响内存效率一般16或32比较合适4. tokenizer_path指定方法4.1 为什么需要指定tokenizer_pathGLM-4-9B-Chat-1M使用特殊的SentencePiece分词器vLLM默认可能无法自动识别。这时候就需要显式指定tokenizer_path。4.2 指定tokenizer_path的三种方法方法1在LLM初始化时指定from vllm import LLM # 方法1直接指定tokenizer路径 llm LLM( model./glm-4-9b-chat-1m, tokenizer./glm-4-9b-chat-1m, # 指定分词器路径 tokenizer_modeauto, # 自动检测分词器类型 trust_remote_codeTrue, max_model_len1048576, ) print(方法1通过tokenizer参数指定)方法2使用tokenizer配置from vllm import LLM from transformers import AutoTokenizer # 方法2先加载分词器再传给vLLM tokenizer AutoTokenizer.from_pretrained( ./glm-4-9b-chat-1m, trust_remote_codeTrue ) llm LLM( model./glm-4-9b-chat-1m, tokenizertokenizer, # 直接传入分词器对象 trust_remote_codeTrue, max_model_len1048576, ) print(方法2传入分词器对象)方法3环境变量指定import os from vllm import LLM # 方法3通过环境变量指定不推荐仅作了解 os.environ[VLLM_TOKENIZER] ./glm-4-9b-chat-1m llm LLM( model./glm-4-9b-chat-1m, trust_remote_codeTrue, max_model_len1048576, ) print(方法3通过环境变量指定)4.3 验证分词器是否正确加载加载后可以验证分词器是否工作正常# 测试分词器 test_text 你好GLM-4-9B-Chat-1M tokens llm.get_tokenizer().encode(test_text) print(f测试文本: {test_text}) print(fToken数量: {len(tokens)}) print(fToken IDs: {tokens}) # 反向测试 decoded llm.get_tokenizer().decode(tokens) print(f解码结果: {decoded}) print(f解码是否一致: {decoded test_text})如果输出显示编码解码一致说明分词器加载正确。5. chat_template注入实战5.1 什么是chat_templatechat_template是定义对话格式的模板。GLM-4-9B-Chat-1M使用特定的对话格式如果不正确设置模型可能无法理解你的输入。5.2 GLM-4-9B-Chat-1M的对话格式GLM-4-9B-Chat-1M使用这样的对话格式[gMASK]sop |user| 你好 |assistant| 你好有什么可以帮助你的吗5.3 方法一修改tokenizer_config.json最简单的方法是在tokenizer_config.json中添加chat_templateimport json # 读取现有的tokenizer配置 with open(./glm-4-9b-chat-1m/tokenizer_config.json, r, encodingutf-8) as f: config json.load(f) # 添加chat_template config[chat_template] {% for message in messages %} {% if message[role] user %} |user| {{ message[content] }} {% elif message[role] assistant %} |assistant| {{ message[content] }} {% elif message[role] system %} {{ message[content] }} {% endif %} {% endfor %} {% if add_generation_prompt %} |assistant| {% endif %} # 保存修改 with open(./glm-4-9b-chat-1m/tokenizer_config.json, w, encodingutf-8) as f: json.dump(config, f, ensure_asciiFalse, indent2) print(chat_template已添加到tokenizer_config.json)5.4 方法二在代码中动态设置如果你不想修改文件可以在代码中动态设置from vllm import LLM from transformers import AutoTokenizer # 加载分词器 tokenizer AutoTokenizer.from_pretrained( ./glm-4-9b-chat-1m, trust_remote_codeTrue ) # 设置chat_template chat_template {% for message in messages %} {% if message[role] user %} |user| {{ message[content] }} {% elif message[role] assistant %} |assistant| {{ message[content] }} {% elif message[role] system %} {{ message[content] }} {% endif %} {% endfor %} {% if add_generation_prompt %} |assistant| {% endif %} tokenizer.chat_template chat_template # 初始化vLLM llm LLM( model./glm-4-9b-chat-1m, tokenizertokenizer, trust_remote_codeTrue, max_model_len1048576, ) print(chat_template已动态设置)5.5 方法三使用apply_chat_templateTransformers库提供了apply_chat_template方法可以更方便地处理对话格式from transformers import AutoTokenizer tokenizer AutoTokenizer.from_pretrained( ./glm-4-9b-chat-1m, trust_remote_codeTrue ) # 定义对话历史 messages [ {role: system, content: 你是一个有帮助的助手。}, {role: user, content: 你好请介绍一下你自己。}, {role: assistant, content: 你好我是GLM-4-9B-Chat-1M一个支持1M上下文的大语言模型。}, {role: user, content: 你能处理多长的文本} ] # 应用chat_template formatted_input tokenizer.apply_chat_template( messages, tokenizeFalse, # 不进行tokenize只格式化 add_generation_promptTrue # 添加生成提示 ) print(格式化后的输入:) print(formatted_input)5.6 验证chat_template是否生效设置完成后验证一下# 测试对话格式 test_messages [ {role: user, content: 你好}, {role: assistant, content: 你好有什么可以帮助你的吗}, {role: user, content: 今天的天气怎么样} ] # 使用分词器格式化 formatted llm.get_tokenizer().apply_chat_template( test_messages, tokenizeFalse, add_generation_promptTrue ) print(格式化后的对话:) print(formatted) print(\n预期的格式:) print([gMASK]sop |user|\n你好\n|assistant|\n你好有什么可以帮助你的吗\n|user|\n今天的天气怎么样\n|assistant|)如果输出格式正确说明chat_template注入成功。6. 完整部署示例6.1 创建完整的部署脚本现在我们把所有配置整合起来创建一个完整的部署脚本# deploy_glm4_1m.py import json from vllm import LLM, SamplingParams from transformers import AutoTokenizer import uvicorn from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import List, Optional import time class ChatMessage(BaseModel): role: str content: str class ChatRequest(BaseModel): messages: List[ChatMessage] max_tokens: Optional[int] 1024 temperature: Optional[float] 0.7 top_p: Optional[float] 0.9 class ChatResponse(BaseModel): response: str usage: dict time_cost: float def initialize_model(): 初始化GLM-4-9B-Chat-1M模型 print(开始初始化GLM-4-9B-Chat-1M模型...) start_time time.time() # 1. 加载并配置分词器 print(1. 加载分词器...) tokenizer AutoTokenizer.from_pretrained( ./glm-4-9b-chat-1m, trust_remote_codeTrue ) # 设置chat_template chat_template {% for message in messages %} {% if message[role] user %} |user| {{ message[content] }} {% elif message[role] assistant %} |assistant| {{ message[content] }} {% elif message[role] system %} {{ message[content] }} {% endif %} {% endfor %} {% if add_generation_prompt %} |assistant| {% endif %} tokenizer.chat_template chat_template print(✓ 分词器配置完成) # 2. 初始化vLLM引擎 print(2. 初始化vLLM引擎...) llm LLM( model./glm-4-9b-chat-1m, tokenizertokenizer, tensor_parallel_size1, gpu_memory_utilization0.85, max_num_seqs128, max_model_len1048576, # 1M上下文 trust_remote_codeTrue, dtypehalf, seed42, enforce_eagerTrue, ) init_time time.time() - start_time print(f✓ 模型初始化完成耗时: {init_time:.2f}秒) print(f✓ 最大上下文长度: {llm.llm_engine.model_config.max_model_len}) return llm # 全局模型实例 llm_instance initialize_model() # 创建FastAPI应用 app FastAPI( titleGLM-4-9B-Chat-1M API, description支持1M上下文的GLM-4-9B-Chat模型API服务, version1.0.0 ) app.post(/chat/completions, response_modelChatResponse) async def chat_completions(request: ChatRequest): 处理聊天补全请求 start_time time.time() try: # 1. 格式化输入 tokenizer llm_instance.get_tokenizer() formatted_input tokenizer.apply_chat_template( [msg.dict() for msg in request.messages], tokenizeFalse, add_generation_promptTrue ) # 2. 设置生成参数 sampling_params SamplingParams( temperaturerequest.temperature, top_prequest.top_p, max_tokensrequest.max_tokens, stop[|endoftext|, |user|] ) # 3. 生成回复 outputs llm_instance.generate( [formatted_input], sampling_paramssampling_params ) # 4. 提取结果 generated_text outputs[0].outputs[0].text # 5. 计算使用量 prompt_tokens len(tokenizer.encode(formatted_input)) completion_tokens len(tokenizer.encode(generated_text)) total_tokens prompt_tokens completion_tokens time_cost time.time() - start_time return ChatResponse( responsegenerated_text, usage{ prompt_tokens: prompt_tokens, completion_tokens: completion_tokens, total_tokens: total_tokens }, time_costtime_cost ) except Exception as e: raise HTTPException(status_code500, detailstr(e)) app.get(/health) async def health_check(): 健康检查端点 return {status: healthy, model: GLM-4-9B-Chat-1M} app.get(/model/info) async def model_info(): 获取模型信息 config llm_instance.llm_engine.model_config return { model_name: GLM-4-9B-Chat-1M, max_model_len: config.max_model_len, vocab_size: config.vocab_size, tensor_parallel_size: config.tensor_parallel_size, dtype: str(config.dtype) } if __name__ __main__: print(\n *50) print(GLM-4-9B-Chat-1M API服务启动中...) print(访问 http://localhost:8000/docs 查看API文档) print(*50 \n) uvicorn.run( app, host0.0.0.0, port8000, log_levelinfo )6.2 启动API服务保存上面的脚本为deploy_glm4_1m.py然后运行python deploy_glm4_1m.py你会看到类似这样的输出开始初始化GLM-4-9B-Chat-1M模型... 1. 加载分词器... ✓ 分词器配置完成 2. 初始化vLLM引擎... ✓ 模型初始化完成耗时: 45.32秒 ✓ 最大上下文长度: 1048576 GLM-4-9B-Chat-1M API服务启动中... 访问 http://localhost:8000/docs 查看API文档 6.3 测试API接口服务启动后可以用curl测试# 测试健康检查 curl http://localhost:8000/health # 测试模型信息 curl http://localhost:8000/model/info # 测试聊天接口 curl -X POST http://localhost:8000/chat/completions \ -H Content-Type: application/json \ -d { messages: [ {role: user, content: 你好请介绍一下GLM-4-9B-Chat-1M的特点} ], max_tokens: 500, temperature: 0.7 }7. 使用chainlit创建Web界面7.1 安装和配置chainlit如果你还没有安装chainlitpip install chainlit7.2 创建chainlit应用创建一个chainlit_app.py文件# chainlit_app.py import chainlit as cl import requests import json from typing import List, Dict # API配置 API_URL http://localhost:8000/chat/completions async def call_glm_api(messages: List[Dict]) - str: 调用GLM-4 API try: payload { messages: messages, max_tokens: 1024, temperature: 0.7, top_p: 0.9 } response requests.post( API_URL, jsonpayload, headers{Content-Type: application/json}, timeout60 ) if response.status_code 200: result response.json() return result[response] else: return fAPI调用失败: {response.status_code} - {response.text} except Exception as e: return f请求出错: {str(e)} cl.on_chat_start async def start_chat(): 聊天开始时的初始化 await cl.Message( content欢迎使用GLM-4-9B-Chat-1M聊天助手\n\n 这是一个支持100万上下文长度的大模型可以处理超长对话。\n 请开始你的对话吧, author系统 ).send() cl.on_message async def handle_message(message: cl.Message): 处理用户消息 # 获取聊天历史 history cl.user_session.get(history, []) # 添加用户消息到历史 history.append({role: user, content: message.content}) # 显示正在思考消息 msg cl.Message(content, authorGLM-4) await msg.send() # 调用API response_text await call_glm_api(history) # 更新消息内容 msg.content response_text await msg.update() # 添加助手回复到历史 history.append({role: assistant, content: response_text}) # 保存历史限制长度避免过长 if len(history) 20: # 保留最近10轮对话 history history[-20:] cl.user_session.set(history, history) cl.on_chat_end async def end_chat(): 聊天结束时的清理 cl.user_session.set(history, []) print(聊天会话结束) # chainlit配置 cl.instrument_openai False # 不使用OpenAI兼容模式 if __name__ __main__: # 运行chainlit应用 from chainlit.cli import run_chainlit run_chainlit(__file__)7.3 启动chainlit界面# 启动chainlit chainlit run chainlit_app.py -w # 或者直接运行 python -m chainlit run chainlit_app.py --port 7860启动后打开浏览器访问http://localhost:7860就能看到聊天界面了。7.4 测试长上下文能力GLM-4-9B-Chat-1M的最大特点是支持1M上下文。你可以测试它的长文本处理能力# 测试长上下文 long_text 这是一段很长的文本... * 10000 # 模拟长文本 messages [ {role: user, content: f请总结以下文本的主要内容\n\n{long_text}} ] # 调用API response call_glm_api(messages) print(f处理长文本响应: {response[:200]}...) # 只打印前200字符8. 常见问题与解决方案8.1 模型加载失败问题ValueError: Failed to load model...可能原因和解决方案模型路径错误检查路径是否正确使用绝对路径权限问题确保有读取权限chmod -R 755 ./glm-4-9b-chat-1m模型文件损坏重新下载模型vLLM版本不兼容尝试pip install vllm0.3.38.2 显存不足问题CUDA out of memory解决方案降低gpu_memory_utilization如0.8启用CPU交换空间swap_space8使用量化版本模型如果有减少max_model_len但会损失长上下文能力8.3 分词器错误问题Tokenizer not found或Unknown tokenizer type解决方案显式指定tokenizer_path确保安装了sentencepiecepip install sentencepiece检查tokenizer_config.json格式是否正确8.4 对话格式错误问题模型回复不符合预期格式解决方案确认chat_template是否正确设置使用apply_chat_template验证格式检查消息列表格式是否正确8.5 性能优化建议批处理同时处理多个请求可以提高吞吐量KV缓存调整block_size优化内存使用量化使用AWQ或GPTQ量化减少显存占用连续批处理vLLM支持连续批处理提高GPU利用率9. 部署总结与建议通过上面的步骤你应该已经成功部署了GLM-4-9B-Chat-1M模型。让我总结一下关键点配置要点回顾engine_args配置重点是max_model_len1048576和trust_remote_codeTruetokenizer_path指定三种方法任选其一确保分词器正确加载chat_template注入必须正确设置对话格式否则模型无法理解输入生产环境建议监控添加Prometheus监控跟踪GPU使用率、响应时间等指标日志记录所有请求和响应便于调试和审计限流实现请求限流防止服务被压垮健康检查定期检查模型服务状态备份定期备份模型权重和配置性能调优根据实际负载调整max_num_seqs和max_num_batched_tokens使用--quantization awq可以显著减少显存占用多GPU环境下合理设置tensor_parallel_size安全考虑API接口添加认证输入内容过滤防止恶意输入输出内容审查确保符合规范限制请求频率防止滥用GLM-4-9B-Chat-1M是一个功能强大的开源模型特别适合需要处理长文本的场景。通过正确的vLLM配置你可以充分发挥它的能力。如果在部署过程中遇到问题可以参考常见问题部分或者查阅vLLM和Transformers的官方文档。记住每个部署环境都有其特殊性可能需要根据实际情况调整配置。最好的方法是先从小规模开始逐步优化直到找到最适合你需求的配置。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。

相关新闻