Ollama平台监控ChatGLM3-6B-128K:性能指标与资源使用分析 Ollama平台监控ChatGLM3-6B-128K性能指标与资源使用分析1. 引言当你把ChatGLM3-6B-128K部署到星图GPU平台后是不是经常想知道这个模型到底运行得怎么样GPU用满了没有内存够不够用响应速度够不够快这些问题其实都很重要特别是当你需要处理长达128K上下文的长文本任务时模型的性能表现直接影响到你的使用体验。今天我就来分享一套完整的监控方案帮你实时掌握ChatGLM3-6B-128K的运行状态及时发现并解决潜在问题。通过本文你将学会如何监控关键性能指标、分析资源使用情况并设置异常报警确保你的模型始终处于最佳运行状态。2. 监控环境准备2.1 基础工具安装首先我们需要安装一些基础的监控工具。在星图GPU平台的实例中执行以下命令# 更新系统包 apt-get update # 安装基础监控工具 apt-get install -y htop nvtop nmon # 安装Python监控库 pip install psutil gpustat prometheus-client这些工具涵盖了系统级监控、GPU监控和Python层面的指标采集为我们后续的监控工作打下基础。2.2 监控目录结构建议创建专门的监控目录来管理相关脚本和配置mkdir -p ~/monitoring/{scripts,config,data} cd ~/monitoring这样的目录结构让监控相关的文件更加有条理便于后续维护和管理。3. 关键性能指标监控3.1 GPU使用情况监控GPU是运行ChatGLM3-6B-128K最重要的资源我们需要重点关注以下几个指标# gpu_monitor.py import gpustat import time import json from datetime import datetime def monitor_gpu(interval5): 监控GPU使用情况 while True: try: stats gpustat.GPUStatCollection.new_query() for gpu in stats: data { timestamp: datetime.now().isoformat(), gpu_index: gpu.index, gpu_utilization: gpu.utilization, memory_used: gpu.memory_used, memory_total: gpu.memory_total, memory_utilization: gpu.memory_used / gpu.memory_total * 100, temperature: gpu.temperature } print(json.dumps(data)) time.sleep(interval) except Exception as e: print(f监控出错: {e}) time.sleep(interval) if __name__ __main__: monitor_gpu()这个脚本会每5秒输出一次GPU的使用情况包括利用率、显存使用、温度等重要指标。3.2 内存和CPU监控除了GPU系统内存和CPU的使用情况也很重要# system_monitor.py import psutil import time import json from datetime import datetime def monitor_system(interval5): 监控系统资源使用情况 while True: try: # CPU使用率 cpu_percent psutil.cpu_percent(interval1) # 内存使用情况 memory psutil.virtual_memory() # 磁盘使用情况 disk psutil.disk_usage(/) data { timestamp: datetime.now().isoformat(), cpu_percent: cpu_percent, memory_used: memory.used, memory_total: memory.total, memory_percent: memory.percent, disk_used: disk.used, disk_total: disk.total, disk_percent: disk.percent } print(json.dumps(data)) time.sleep(interval) except Exception as e: print(f系统监控出错: {e}) time.sleep(interval) if __name__ __main__: monitor_system()4. ChatGLM3特定指标监控4.1 推理性能指标对于ChatGLM3-6B-128K我们还需要监控一些模型特有的指标# model_monitor.py import time import json from datetime import datetime class ModelPerformanceMonitor: def __init__(self): self.inference_times [] self.tokens_per_second [] self.throughput [] def record_inference(self, input_length, output_length, inference_time): 记录推理性能数据 data { timestamp: datetime.now().isoformat(), input_tokens: input_length, output_tokens: output_length, inference_time: inference_time, tokens_per_second: output_length / inference_time if inference_time 0 else 0, throughput: (input_length output_length) / inference_time if inference_time 0 else 0 } self.inference_times.append(inference_time) self.tokens_per_second.append(data[tokens_per_second]) self.throughput.append(data[throughput]) # 保持最近1000条记录 if len(self.inference_times) 1000: self.inference_times self.inference_times[-1000:] self.tokens_per_second self.tokens_per_second[-1000:] self.throughput self.throughput[-1000:] return data def get_stats(self): 获取统计信息 if not self.inference_times: return {} return { avg_inference_time: sum(self.inference_times) / len(self.inference_times), avg_tokens_per_second: sum(self.tokens_per_second) / len(self.tokens_per_second), avg_throughput: sum(self.throughput) / len(self.throughput), total_inferences: len(self.inference_times) } # 全局监控实例 model_monitor ModelPerformanceMonitor()4.2 长文本处理监控由于ChatGLM3-6B-128K专门针对长文本优化我们需要特别关注长文本处理的性能# long_text_monitor.py import time import json from datetime import datetime class LongTextMonitor: def __init__(self): self.long_text_stats [] def monitor_long_text_processing(self, context_length, processing_time, successTrue): 监控长文本处理性能 data { timestamp: datetime.now().isoformat(), context_length: context_length, processing_time: processing_time, tokens_per_second: context_length / processing_time if processing_time 0 else 0, success: success } self.long_text_stats.append(data) # 保持最近500条记录 if len(self.long_text_stats) 500: self.long_text_stats self.long_text_stats[-500:] return data def get_long_text_stats(self, min_length8000): 获取长文本处理统计信息 long_texts [stat for stat in self.long_text_stats if stat[context_length] min_length and stat[success]] if not long_texts: return {} return { avg_processing_time: sum(stat[processing_time] for stat in long_texts) / len(long_texts), avg_tokens_per_second: sum(stat[tokens_per_second] for stat in long_texts) / len(long_texts), total_long_texts_processed: len(long_texts) } # 全局长文本监控实例 long_text_monitor LongTextMonitor()5. 实时监控仪表板5.1 使用Grafana创建监控面板虽然星图GPU平台可能已经提供了一些监控功能但我们也可以自己搭建更详细的监控面板。首先安装和配置Grafana# 安装Grafana wget https://dl.grafana.com/oss/release/grafana_10.4.1_amd64.deb sudo dpkg -i grafana_10.4.1_amd64.deb sudo systemctl start grafana-server sudo systemctl enable grafana-server5.2 监控数据收集器创建一个数据收集器将监控数据发送到Grafana# metrics_collector.py import requests import time import json from system_monitor import monitor_system from gpu_monitor import monitor_gpu class MetricsCollector: def __init__(self, grafana_url): self.grafana_url grafana_url self.metrics_buffer [] def send_metrics(self, metrics): 发送指标到监控系统 try: headers {Content-Type: application/json} response requests.post( f{self.grafana_url}/api/metrics, datajson.dumps(metrics), headersheaders, timeout5 ) return response.status_code 200 except Exception as e: print(f发送指标失败: {e}) return False def collect_metrics(self): 收集所有监控指标 while True: try: # 收集系统指标 system_metrics monitor_system() # 收集GPU指标 gpu_metrics monitor_gpu() # 收集模型性能指标 model_metrics model_monitor.get_stats() # 收集长文本处理指标 long_text_metrics long_text_monitor.get_long_text_stats() # 合并所有指标 all_metrics { timestamp: time.time(), system: system_metrics, gpu: gpu_metrics, model: model_metrics, long_text: long_text_metrics } # 发送指标 self.send_metrics(all_metrics) time.sleep(30) # 每30秒发送一次 except Exception as e: print(f收集指标出错: {e}) time.sleep(30) if __name__ __main__: collector MetricsCollector(http://localhost:3000) collector.collect_metrics()6. 异常检测与报警设置6.1 基于规则的异常检测设置一些基本的规则来检测异常情况# anomaly_detector.py import time from datetime import datetime import smtplib from email.mime.text import MIMEText class AnomalyDetector: def __init__(self, alert_emailNone): self.alert_email alert_email self.last_alert_time {} def check_anomalies(self, metrics): 检查指标异常 anomalies [] # GPU使用率异常 if metrics[gpu][gpu_utilization] 95: anomalies.append(GPU使用率超过95%) # 显存不足警告 memory_utilization metrics[gpu][memory_used] / metrics[gpu][memory_total] * 100 if memory_utilization 90: anomalies.append(显存使用率超过90%) # 温度过高警告 if metrics[gpu][temperature] 85: anomalies.append(GPU温度超过85°C) # 系统内存不足 if metrics[system][memory_percent] 90: anomalies.append(系统内存使用率超过90%) return anomalies def send_alert(self, message): 发送报警通知 if not self.alert_email: return # 防止频繁报警同一类型报警至少间隔1小时 alert_key hash(message) current_time time.time() if alert_key in self.last_alert_time: if current_time - self.last_alert_time[alert_key] 3600: return try: # 这里简化了邮件发送逻辑实际使用时需要配置SMTP服务器 msg MIMEText(message) msg[Subject] ChatGLM3监控报警 msg[From] monitorexample.com msg[To] self.alert_email # 实际使用时需要配置SMTP服务器 # with smtplib.SMTP(smtp.example.com) as server: # server.send_message(msg) print(f报警通知: {message}) self.last_alert_time[alert_key] current_time except Exception as e: print(f发送报警失败: {e}) def monitor_and_alert(self, metrics): 监控并发送报警 anomalies self.check_anomalies(metrics) for anomaly in anomalies: self.send_alert(f{datetime.now()}: {anomaly}) # 使用示例 detector AnomalyDetector(alert_emailyour-emailexample.com)6.2 基于机器学习的异常检测对于更高级的异常检测我们可以使用机器学习方法# ml_anomaly_detector.py import numpy as np from sklearn.ensemble import IsolationForest from collections import deque class MLAnomalyDetector: def __init__(self, window_size100): self.window_size window_size self.metrics_history deque(maxlenwindow_size) self.detector IsolationForest(contamination0.1) self.is_trained False def add_metrics(self, metrics): 添加指标到历史数据 # 提取数值特征 features [ metrics[gpu][gpu_utilization], metrics[gpu][memory_used] / metrics[gpu][memory_total], metrics[system][cpu_percent], metrics[system][memory_percent] / 100 ] self.metrics_history.append(features) # 当有足够数据时训练检测器 if len(self.metrics_history) self.window_size and not self.is_trained: self.train_detector() def train_detector(self): 训练异常检测器 X np.array(list(self.metrics_history)) self.detector.fit(X) self.is_trained True def detect_anomaly(self, metrics): 检测异常 if not self.is_trained: return False features [ metrics[gpu][gpu_utilization], metrics[gpu][memory_used] / metrics[gpu][memory_total], metrics[system][cpu_percent], metrics[system][memory_percent] / 100 ] prediction self.detector.predict([features]) return prediction[0] -1 # -1表示异常7. 监控数据分析和优化建议7.1 性能数据分析通过监控数据我们可以分析模型的性能特征# performance_analyzer.py import numpy as np import json from datetime import datetime, timedelta class PerformanceAnalyzer: def __init__(self): self.performance_data [] def analyze_performance_trends(self, hours24): 分析性能趋势 end_time datetime.now() start_time end_time - timedelta(hourshours) # 过滤指定时间范围内的数据 recent_data [ data for data in self.performance_data if start_time datetime.fromisoformat(data[timestamp]) end_time ] if not recent_data: return {} # 计算各种统计指标 inference_times [data[inference_time] for data in recent_data] throughputs [data[throughput] for data in recent_data] return { time_period: f最近{hours}小时, total_inferences: len(recent_data), avg_inference_time: np.mean(inference_times), max_inference_time: np.max(inference_times), min_inference_time: np.min(inference_times), avg_throughput: np.mean(throughputs), p95_inference_time: np.percentile(inference_times, 95), p99_inference_time: np.percentile(inference_times, 99) } def generate_optimization_suggestions(self, metrics): 生成优化建议 suggestions [] # GPU相关建议 if metrics[gpu][gpu_utilization] 50: suggestions.append(GPU利用率较低可以考虑增加并发请求数量) if metrics[gpu][memory_used] / metrics[gpu][memory_total] 0.9: suggestions.append(显存使用率较高建议优化模型或减少批量大小) # 系统资源建议 if metrics[system][memory_percent] 90: suggestions.append(系统内存使用率过高建议增加内存或优化程序) # 性能建议 perf_stats self.analyze_performance_trends() if perf_stats.get(p95_inference_time, 0) 10: # 假设10秒为阈值 suggestions.append(推理时间较长建议检查模型配置或硬件性能) return suggestions7.2 资源使用优化建议基于监控数据提供具体的优化建议# resource_optimizer.py class ResourceOptimizer: staticmethod def optimize_based_on_metrics(metrics): 基于监控指标提供优化建议 recommendations [] gpu_util metrics[gpu][gpu_utilization] memory_util metrics[gpu][memory_used] / metrics[gpu][memory_total] if gpu_util 40: recommendations.append({ type: 性能, suggestion: GPU利用率较低可以增加并发处理任务, priority: 中等 }) if memory_util 0.85: recommendations.append({ type: 资源, suggestion: 显存使用率较高建议减少批量大小或使用梯度累积, priority: 高 }) if metrics[system][memory_percent] 85: recommendations.append({ type: 资源, suggestion: 系统内存不足建议增加Swap空间或优化数据加载, priority: 高 }) # 根据长文本处理性能提供建议 long_text_stats metrics.get(long_text, {}) if long_text_stats.get(avg_processing_time, 0) 30: # 30秒阈值 recommendations.append({ type: 性能, suggestion: 长文本处理时间较长建议优化文本分割策略, priority: 中等 }) return recommendations8. 总结通过这套完整的监控方案你应该能够全面掌握ChatGLM3-6B-128K在星图GPU平台上的运行状态。从基础的GPU和系统监控到模型特有的性能指标再到异常检测和优化建议这套方案覆盖了模型运维的各个方面。实际使用中你可能需要根据具体的业务需求调整监控指标和报警阈值。比如如果你的应用对响应时间特别敏感就需要设置更严格的推理时间监控如果你主要处理长文本任务那么就需要更关注内存使用和长文本处理性能。监控的目的不是为了收集数据而是为了从中获得洞察优化模型性能提升用户体验。建议定期回顾监控数据分析性能趋势及时发现潜在问题这样才能确保你的ChatGLM3-6B-128K实例始终处于最佳运行状态。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。