Qwen-Image镜像实操手册Qwen-VL推理服务封装为FastAPI接口完整示例1. 环境准备与快速部署1.1 镜像基础配置Qwen-Image定制镜像已经预装了运行Qwen-VL模型所需的所有依赖包括CUDA 12.4 cuDNNGPU加速完整依赖Python 3.xQwen官方推荐版本PyTorch GPU版本适配CUDA12.4Qwen-VL推理依赖库常用图像处理工具包启动实例后可以通过以下命令验证环境# 检查GPU状态 nvidia-smi # 验证CUDA版本 nvcc -V # 检查Python版本 python --version1.2 模型文件准备将Qwen-VL模型文件存放在/data路径下这是镜像默认挂载的数据盘# 创建模型目录 mkdir -p /data/models/qwen-vl # 假设模型文件已下载到本地使用scp上传 scp -r local_model_path useryour_instance_ip:/data/models/qwen-vl2. 基础推理脚本编写2.1 创建基础推理脚本在工作目录下创建qwen_vl_inference.py文件import torch from transformers import AutoModelForCausalLM, AutoTokenizer from PIL import Image # 初始化模型和tokenizer model_path /data/models/qwen-vl device cuda if torch.cuda.is_available() else cpu tokenizer AutoTokenizer.from_pretrained(model_path, trust_remote_codeTrue) model AutoModelForCausalLM.from_pretrained( model_path, device_mapauto, trust_remote_codeTrue ).eval() def infer(image_path, question): 基础推理函数 image Image.open(image_path).convert(RGB) query fimg{image_path}/img{question} inputs tokenizer.from_list_format([{image: image_path}]) response, history model.chat(tokenizer, queryquery, historyNone) return response2.2 测试基础推理功能创建一个简单的测试脚本test_inference.pyfrom qwen_vl_inference import infer # 测试图片和问题 image_path /data/test_images/dog.jpg question 图片中是什么动物 # 执行推理 result infer(image_path, question) print(f问题: {question}) print(f回答: {result})运行测试脚本确保基础功能正常python test_inference.py3. FastAPI接口封装3.1 安装FastAPI及相关依赖虽然镜像已经预装了大部分依赖但需要额外安装FastAPI和uvicornpip install fastapi uvicorn3.2 创建FastAPI应用创建app.py文件封装完整的API服务from fastapi import FastAPI, UploadFile, File, Form from fastapi.responses import JSONResponse from PIL import Image import io import os import uuid from typing import Optional app FastAPI( titleQwen-VL推理API, description基于Qwen-Image镜像的视觉语言模型推理服务, version1.0 ) # 初始化模型同上 # ... app.post(/v1/chat) async def chat_with_image( image: UploadFile File(...), question: str Form(...), temperature: Optional[float] Form(0.7), max_length: Optional[int] Form(2048) ): 图文对话接口 try: # 保存上传的图片 image_data await image.read() image_path f/data/temp/{str(uuid.uuid4())}.jpg with open(image_path, wb) as f: f.write(image_data) # 执行推理 response infer(image_path, question) # 清理临时文件 os.remove(image_path) return JSONResponse({ status: success, response: response }) except Exception as e: return JSONResponse({ status: error, message: str(e) }, status_code500) app.get(/health) async def health_check(): 健康检查接口 return {status: healthy}3.3 创建启动脚本创建start_server.sh启动脚本#!/bin/bash # 创建临时目录 mkdir -p /data/temp # 启动FastAPI服务 uvicorn app:app --host 0.0.0.0 --port 8000 --workers 2给脚本添加执行权限chmod x start_server.sh4. 服务部署与测试4.1 启动服务运行启动脚本./start_server.sh服务启动后默认监听8000端口。可以通过以下命令检查服务是否正常运行curl http://localhost:8000/health4.2 测试API接口使用Python的requests库测试APIimport requests url http://your_instance_ip:8000/v1/chat with open(test_image.jpg, rb) as image_file: files {image: image_file} data {question: 描述这张图片的内容} response requests.post(url, filesfiles, datadata) print(response.json())或者使用curl命令测试curl -X POST -F imagetest_image.jpg -F question描述这张图片的内容 http://localhost:8000/v1/chat5. 性能优化与生产部署建议5.1 性能优化技巧批处理支持修改API支持批量图片处理缓存机制对常见问题答案进行缓存模型量化使用4bit或8bit量化减少显存占用异步处理使用Celery处理长时间推理任务5.2 生产部署建议使用Nginx反向代理提高并发处理能力启用HTTPS保证数据传输安全添加认证使用API密钥保护接口监控与日志集成Prometheus和Grafana监控6. 总结通过本教程我们完成了以下工作在Qwen-Image定制镜像上部署了Qwen-VL模型编写了基础推理脚本并验证功能使用FastAPI封装了完整的推理API服务测试了API接口并验证功能正常讨论了性能优化和生产部署建议现在你已经拥有了一个可以在RTX4090D上高效运行的Qwen-VL推理服务可以轻松集成到各种应用中如图文客服、智能相册、内容审核等场景。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。
Qwen-Image镜像实操手册:Qwen-VL推理服务封装为FastAPI接口完整示例
Qwen-Image镜像实操手册Qwen-VL推理服务封装为FastAPI接口完整示例1. 环境准备与快速部署1.1 镜像基础配置Qwen-Image定制镜像已经预装了运行Qwen-VL模型所需的所有依赖包括CUDA 12.4 cuDNNGPU加速完整依赖Python 3.xQwen官方推荐版本PyTorch GPU版本适配CUDA12.4Qwen-VL推理依赖库常用图像处理工具包启动实例后可以通过以下命令验证环境# 检查GPU状态 nvidia-smi # 验证CUDA版本 nvcc -V # 检查Python版本 python --version1.2 模型文件准备将Qwen-VL模型文件存放在/data路径下这是镜像默认挂载的数据盘# 创建模型目录 mkdir -p /data/models/qwen-vl # 假设模型文件已下载到本地使用scp上传 scp -r local_model_path useryour_instance_ip:/data/models/qwen-vl2. 基础推理脚本编写2.1 创建基础推理脚本在工作目录下创建qwen_vl_inference.py文件import torch from transformers import AutoModelForCausalLM, AutoTokenizer from PIL import Image # 初始化模型和tokenizer model_path /data/models/qwen-vl device cuda if torch.cuda.is_available() else cpu tokenizer AutoTokenizer.from_pretrained(model_path, trust_remote_codeTrue) model AutoModelForCausalLM.from_pretrained( model_path, device_mapauto, trust_remote_codeTrue ).eval() def infer(image_path, question): 基础推理函数 image Image.open(image_path).convert(RGB) query fimg{image_path}/img{question} inputs tokenizer.from_list_format([{image: image_path}]) response, history model.chat(tokenizer, queryquery, historyNone) return response2.2 测试基础推理功能创建一个简单的测试脚本test_inference.pyfrom qwen_vl_inference import infer # 测试图片和问题 image_path /data/test_images/dog.jpg question 图片中是什么动物 # 执行推理 result infer(image_path, question) print(f问题: {question}) print(f回答: {result})运行测试脚本确保基础功能正常python test_inference.py3. FastAPI接口封装3.1 安装FastAPI及相关依赖虽然镜像已经预装了大部分依赖但需要额外安装FastAPI和uvicornpip install fastapi uvicorn3.2 创建FastAPI应用创建app.py文件封装完整的API服务from fastapi import FastAPI, UploadFile, File, Form from fastapi.responses import JSONResponse from PIL import Image import io import os import uuid from typing import Optional app FastAPI( titleQwen-VL推理API, description基于Qwen-Image镜像的视觉语言模型推理服务, version1.0 ) # 初始化模型同上 # ... app.post(/v1/chat) async def chat_with_image( image: UploadFile File(...), question: str Form(...), temperature: Optional[float] Form(0.7), max_length: Optional[int] Form(2048) ): 图文对话接口 try: # 保存上传的图片 image_data await image.read() image_path f/data/temp/{str(uuid.uuid4())}.jpg with open(image_path, wb) as f: f.write(image_data) # 执行推理 response infer(image_path, question) # 清理临时文件 os.remove(image_path) return JSONResponse({ status: success, response: response }) except Exception as e: return JSONResponse({ status: error, message: str(e) }, status_code500) app.get(/health) async def health_check(): 健康检查接口 return {status: healthy}3.3 创建启动脚本创建start_server.sh启动脚本#!/bin/bash # 创建临时目录 mkdir -p /data/temp # 启动FastAPI服务 uvicorn app:app --host 0.0.0.0 --port 8000 --workers 2给脚本添加执行权限chmod x start_server.sh4. 服务部署与测试4.1 启动服务运行启动脚本./start_server.sh服务启动后默认监听8000端口。可以通过以下命令检查服务是否正常运行curl http://localhost:8000/health4.2 测试API接口使用Python的requests库测试APIimport requests url http://your_instance_ip:8000/v1/chat with open(test_image.jpg, rb) as image_file: files {image: image_file} data {question: 描述这张图片的内容} response requests.post(url, filesfiles, datadata) print(response.json())或者使用curl命令测试curl -X POST -F imagetest_image.jpg -F question描述这张图片的内容 http://localhost:8000/v1/chat5. 性能优化与生产部署建议5.1 性能优化技巧批处理支持修改API支持批量图片处理缓存机制对常见问题答案进行缓存模型量化使用4bit或8bit量化减少显存占用异步处理使用Celery处理长时间推理任务5.2 生产部署建议使用Nginx反向代理提高并发处理能力启用HTTPS保证数据传输安全添加认证使用API密钥保护接口监控与日志集成Prometheus和Grafana监控6. 总结通过本教程我们完成了以下工作在Qwen-Image定制镜像上部署了Qwen-VL模型编写了基础推理脚本并验证功能使用FastAPI封装了完整的推理API服务测试了API接口并验证功能正常讨论了性能优化和生产部署建议现在你已经拥有了一个可以在RTX4090D上高效运行的Qwen-VL推理服务可以轻松集成到各种应用中如图文客服、智能相册、内容审核等场景。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。