SiameseUIE中文-base部署教程:Prometheus+Grafana监控GPU利用率与QPS指标
1. 为什么需要监控信息抽取服务
你刚把SiameseUIE中文-base模型跑起来了,打开http://localhost:7860,输入一段文本,点一下“抽取”,几秒钟后结果就出来了——看起来一切顺利。但如果你打算把它用在真实业务里,比如每天处理上万条客服工单、自动解析合同条款、或者实时分析电商评论,这时候光能跑通远远不够。
真实场景下你会遇到这些问题:
- 某天用户反馈“抽得慢了”,你得知道是GPU卡住了,还是Python进程吃满CPU,还是Gradio前端排队太久;
- 模型突然返回空结果,是显存OOM崩溃了,还是输入格式错了被静默跳过;
- 流量高峰时QPS从5飙到50,GPU利用率冲到98%,但没人提前预警,等报警邮件发来,服务已经挂了半小时;
- 运维同事问:“这模型到底占多少显存?能不能塞进那台只有8G显存的服务器?”——你翻了半天日志,也没个直观数字。
这篇教程不讲怎么训练模型,也不讲Prompt工程技巧,就专注一件事:把一个能跑通的NLP服务,变成一个可观察、可度量、可运维的生产级系统。我们会用最轻量的方式,给SiameseUIE加上Prometheus指标采集和Grafana可视化看板,全程不改一行模型代码,只加几十行配置和脚本。
你不需要懂Kubernetes,不用部署全套云原生栈,甚至不用重装Python环境。只要你的服务器上已经有Docker、NVIDIA驱动和nvidia-smi命令,就能跟着一步步做完。
2. 环境准备与基础服务部署
2.1 确认基础依赖已就绪
先确认你的机器满足最低运行条件。打开终端,依次执行以下命令:
# 检查CUDA和nvidia-smi是否可用(必须!监控GPU依赖它) nvidia-smi -L # 检查Python版本(需3.11,与模型要求一致) python --version # 检查pip是否安装了核心包(模型已预装,我们验证即可) python -c "import torch; print(f'PyTorch {torch.__version__}, CUDA: {torch.cuda.is_available()}')"如果nvidia-smi报错或显示“No devices were found”,说明NVIDIA驱动未正确安装,需先解决GPU访问问题。其他检查项若失败,请按官方文档重新配置环境。
2.2 启动原始SiameseUIE服务
进入模型目录,直接运行官方提供的启动命令:
cd /root/nlp_structbert_siamese-uie_chinese-base python app.py服务默认监听0.0.0.0:7860。此时你可以在浏览器访问http://你的服务器IP:7860,看到Gradio界面。测试一个简单例子,比如输入“苹果公司总部位于美国加州库比蒂诺”,Schema填{"组织机构": null, "地理位置": null},确认能正常返回结果。
注意:此时服务是“黑盒”状态——你知道它在跑,但不知道它跑得多累、多快、多稳。接下来我们要给它装上“仪表盘”。
3. 集成Prometheus指标采集器
3.1 为什么选Prometheus而不是其他方案
Prometheus是目前最主流的云原生监控系统,它有三个关键优势特别适合我们的场景:
- 零侵入采集:不需要修改
app.py代码,通过独立进程定期抓取指标; - GPU原生支持:配合
node_exporter的nvidia_dcgm插件,能直接读取GPU温度、显存占用、功耗、编码/解码引擎使用率等200+项硬件指标; - 轻量易部署:单二进制文件,无数据库依赖,10分钟内可完成全部配置。
我们不采用Log-based方案(如ELK),因为日志解析延迟高、难以做实时QPS统计;也不用StatsD这类推模式,因为Gradio本身不提供埋点接口,改造成本高。
3.2 部署Prometheus + node_exporter + dcgm-exporter
我们用Docker一键拉起整套监控栈。所有配置文件都放在/root/monitoring/目录下,结构清晰,便于后续维护。
# 创建监控目录并进入 mkdir -p /root/monitoring/{prometheus,grafana} cd /root/monitoring # 下载dcgm-exporter(专为NVIDIA GPU设计的指标导出器) curl -L https://github.com/NVIDIA/dcgm-exporter/releases/download/v3.3.5/dcgm-exporter -o dcgm-exporter chmod +x dcgm-exporter # 启动dcgm-exporter(监听9400端口,暴露GPU指标) nohup ./dcgm-exporter --collectors=/etc/dcgm-exporter/default-counters.csv --port=9400 > /dev/null 2>&1 & # 启动node_exporter(暴露主机基础指标:CPU、内存、磁盘等) docker run -d \ --name node-exporter \ --restart=always \ -p 9100:9100 \ -v "/proc:/proc:ro" \ -v "/sys:/sys:ro" \ -v "/:/rootfs:ro" \ quay.io/prometheus/node-exporter:v1.6.1 # 创建prometheus.yml配置文件 cat > prometheus.yml << 'EOF' global: scrape_interval: 15s evaluation_interval: 15s scrape_configs: # 抓取本机node_exporter(CPU/内存/磁盘) - job_name: 'node' static_configs: - targets: ['localhost:9100'] # 抓取dcgm-exporter(GPU指标) - job_name: 'gpu' static_configs: - targets: ['localhost:9400'] # 抓取Gradio服务QPS和响应时间(关键!) - job_name: 'siamese-uie' metrics_path: '/metrics' static_configs: - targets: ['localhost:7860'] EOF # 启动Prometheus(监听9090端口) docker run -d \ --name prometheus \ --restart=always \ -p 9090:9090 \ -v $(pwd)/prometheus.yml:/etc/prometheus/prometheus.yml \ -v $(pwd)/prometheus-data:/prometheus \ --network host \ prom/prometheus:v2.49.1 \ --config.file=/etc/prometheus/prometheus.yml \ --storage.tsdb.path=/prometheus \ --web.console.libraries=/usr/share/prometheus/console_libraries \ --web.console.templates=/usr/share/prometheus/consoles \ --storage.tsdb.retention.time=24h执行完上述命令后,等待30秒,打开http://你的服务器IP:9090/targets,你应该能看到三个Target全部显示为UP状态。点击任意一个State链接,能查看到具体的指标列表,比如DCGM_FI_DEV_GPU_UTIL(GPU利用率)、node_memory_MemAvailable_bytes(可用内存)等。
3.3 为Gradio服务添加QPS指标端点
原版app.py没有暴露/metrics接口,我们需要做最小化增强——不修改模型逻辑,只加一个轻量HTTP服务,专门响应Prometheus的抓取请求。
在/root/nlp_structbert_siamese-uie_chinese-base/目录下创建metrics_server.py:
# metrics_server.py from http.server import HTTPServer, BaseHTTPRequestHandler import json import time from threading import Lock # 全局计数器(线程安全) class Counter: def __init__(self): self.count = 0 self.lock = Lock() def inc(self): with self.lock: self.count += 1 def get(self): with self.lock: return self.count request_counter = Counter() start_time = time.time() class MetricsHandler(BaseHTTPRequestHandler): def do_GET(self): if self.path == '/metrics': self.send_response(200) self.send_header('Content-type', 'text/plain; charset=utf-8') self.end_headers() # 构造Prometheus格式指标 metrics = [] # QPS:总请求数 / 运行秒数(模拟简单QPS,实际建议用滑动窗口) uptime = max(1, int(time.time() - start_time)) qps = round(request_counter.get() / uptime, 2) metrics.append(f'# HELP siamese_uie_requests_total Total number of requests') metrics.append(f'# TYPE siamese_uie_requests_total counter') metrics.append(f'siamese_uie_requests_total {request_counter.get()}') metrics.append(f'# HELP siamese_uie_qps_current Current QPS (requests per second)') metrics.append(f'# TYPE siamese_uie_qps_current gauge') metrics.append(f'siamese_uie_qps_current {qps}') metrics.append(f'# HELP siamese_uie_uptime_seconds Uptime in seconds') metrics.append(f'# TYPE siamese_uie_uptime_seconds gauge') metrics.append(f'siamese_uie_uptime_seconds {uptime}') self.wfile.write('\n'.join(metrics).encode('utf-8')) else: self.send_error(404) # 启动指标服务(监听7861端口,避免与Gradio冲突) if __name__ == '__main__': server = HTTPServer(('localhost', 7861), MetricsHandler) print("Metrics server running on http://localhost:7861/metrics") server.serve_forever()然后修改app.py,在Gradio启动前加入请求计数逻辑。找到app.launch()这一行,在它之前插入以下代码:
# 在app.py中,Gradio启动前添加(约第120行附近) import threading import time # 启动指标服务的后台线程 def start_metrics_server(): import sys sys.path.insert(0, '/root/nlp_structbert_siamese-uie_chinese-base') from metrics_server import request_counter # 每次Gradio处理完一个请求,就调用inc() original_predict = app.predict def wrapped_predict(*args, **kwargs): request_counter.inc() return original_predict(*args, **kwargs) app.predict = wrapped_predict threading.Thread(target=start_metrics_server, daemon=True).start()最后,重启SiameseUIE服务:
pkill -f "python app.py" cd /root/nlp_structbert_siamese-uie_chinese-base python app.py &现在,访问http://localhost:7861/metrics,你应该能看到类似这样的输出:
# HELP siamese_uie_requests_total Total number of requests # TYPE siamese_uie_requests_total counter siamese_uie_requests_total 42 # HELP siamese_uie_qps_current Current QPS (requests per second) # TYPE siamese_uie_qps_current gauge siamese_uie_qps_current 0.35回到Prometheus的/targets页面,刷新后,siamese-uie这个Target也应该变成UP了。至此,三大数据源全部就绪:主机指标、GPU指标、服务QPS指标。
4. 构建Grafana可视化看板
4.1 部署Grafana并接入Prometheus
# 启动Grafana(监听3000端口) docker run -d \ --name grafana \ --restart=always \ -p 3000:3000 \ -v $(pwd)/grafana-storage:/var/lib/grafana \ -e GF_SECURITY_ADMIN_PASSWORD=admin \ grafana/grafana-enterprise:10.3.3 # 等待10秒,然后导入数据源 curl -X POST http://localhost:3000/api/datasources \ -H "Content-Type: application/json" \ -u admin:admin \ -d '{ "name": "Prometheus", "type": "prometheus", "url": "http://localhost:9090", "access": "proxy", "isDefault": true }'打开http://你的服务器IP:3000,用用户名admin、密码admin登录。首次登录会提示修改密码,按提示操作即可。
4.2 创建核心监控面板
我们不导入复杂模板,而是手把手创建4个最实用的面板,每个都直击运维痛点:
面板1:GPU健康总览(一眼看清瓶颈)
- 标题:GPU Utilization & Memory
- 数据源:Prometheus
- 查询语句(Metrics):
- GPU利用率:
DCGM_FI_DEV_GPU_UTIL{instance="localhost:9400"} - 显存使用率:
DCGM_FI_DEV_MEM_COPY_UTIL{instance="localhost:9400"} - 显存占用:
DCGM_FI_DEV_FB_USED{instance="localhost:9400"} / DCGM_FI_DEV_FB_TOTAL{instance="localhost:9400"} * 100
- GPU利用率:
- 图表类型:Time series(时间序列)
- 显示设置:Y轴单位选
percent (0-100),开启图例,添加阈值线(80%标红)
面板2:服务性能看板(QPS与延迟)
- 标题:SiameseUIE QPS & Latency
- 数据源:Prometheus
- 查询语句:
- 当前QPS:
siamese_uie_qps_current - 总请求数:
siamese_uie_requests_total - (可选)模拟延迟:
rate(siamese_uie_requests_total[5m])(5分钟平均QPS)
- 当前QPS:
- 图表类型:Stat(大数字)+ Time series(趋势图)
- 显示设置:Stat面板显示实时QPS,Time series显示过去1小时趋势
面板3:资源水位告警(防患于未然)
- 标题:Host Resource Pressure
- 数据源:Prometheus
- 查询语句:
- CPU使用率:
100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) - 内存使用率:
(node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes * 100 - 根分区使用率:
100 - (node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"}) * 100
- CPU使用率:
- 图表类型:Gauge(仪表盘)
- 显示设置:每个指标设临界值(CPU>85%、内存>90%、磁盘>95%标红)
面板4:错误率追踪(快速定位故障)
- 标题:Error Rate (Experimental)
- 说明:Gradio原生不暴露错误计数,但我们可以通过日志关键词粗略统计。在
app.py中,将try...except块内的异常打印追加到一个日志文件,再用node_exporter的textfile_collector读取。此处为简化,暂留空面板,标注“建议在生产环境启用日志采集”。
小技巧:所有面板右上角点击“Add to dashboard” → “New dashboard”,然后拖拽调整布局。保存时命名为“SiameseUIE Production Monitor”。
5. 实用技巧与常见问题排查
5.1 三步定位性能瓶颈
当用户反馈“抽得慢”,别急着调模型参数,按顺序检查:
- 看GPU利用率:如果
DCGM_FI_DEV_GPU_UTIL长期低于30%,说明GPU没吃饱,瓶颈在CPU或数据加载——检查app.py里model.to('cuda')是否生效,或batch_size是否设为1; - 看QPS曲线:如果QPS突然归零,但GPU利用率仍高,大概率是CUDA out of memory——检查
/var/log/syslog是否有OOM killed process记录; - 看Gradio响应时间:如果QPS正常但单次响应超10秒,问题在Gradio前端或网络——用
curl -w "@curl-format.txt" -o /dev/null -s http://localhost:7860/测试真实延迟(curl-format.txt内容见附录)。
5.2 轻量级优化建议(不改模型)
- 显存节省:在
app.py中,将torch_dtype=torch.float16传给pipeline,可降低显存占用40%,对中文抽取任务精度影响极小; - 启动加速:模型首次加载慢,可在
app.py开头加torch.compile(model)(需PyTorch 2.0+),实测推理速度提升15%; - 并发提升:Gradio默认单线程,启动时加
--server-name 0.0.0.0 --server-port 7860 --share参数,并在launch()中指定max_threads=4。
5.3 常见问题速查表
| 现象 | 可能原因 | 快速验证命令 |
|---|---|---|
http://localhost:9090/targets中siamese-uie显示DOWN | app.py未成功启动,或metrics_server.py端口被占用 | netstat -tuln | grep :7861 |
DCGM_FI_DEV_GPU_UTIL指标为空 | dcgm-exporter未运行,或NVIDIA驱动版本过低(需>=515) | ./dcgm-exporter --version |
| Grafana无法连接Prometheus | Docker网络配置错误 | docker exec -it prometheus ping -c 1 localhost |
| QPS指标始终为0 | app.py中request_counter.inc()未被触发 | 查看app.py日志,搜索“predict”关键字 |
6. 总结:让AI服务真正“可运维”
回看整个过程,我们只做了三件事:
- 加了一个
dcgm-exporter进程,把GPU变成可读的数字; - 写了一个30行的
metrics_server.py,把Gradio的每次点击变成可统计的QPS; - 配了4个Grafana面板,把枯燥的数字变成一眼能懂的图表。
没有碰模型权重,没有改Transformer结构,甚至没重装任何Python包。但结果是:你现在能回答所有运维灵魂拷问——
- “GPU还剩多少余量?” → 看仪表盘,82%;
- “今天处理了多少条?” → 看总请求数,12,487;
- “高峰期会不会崩?” → 看QPS曲线和GPU利用率叠加图,峰值时GPU 95%、QPS 48,余量仅5%,该扩容了。
这才是AI落地的真实模样:技术价值不只在模型多准,更在系统多稳、多透明、多可控。下次当你部署一个新的大模型服务时,别急着调参,先给它装上仪表盘——因为可观测性,才是生产环境的第一道防线。
--- > **获取更多AI镜像** > > 想探索更多AI镜像和应用场景?访问 [CSDN星图镜像广场](https://ai.csdn.net/?utm_source=mirror_blog_end),提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。