转载请注明出处:小锋学长生活大爆炸[xfxuezhagn.cn] 如果本文帮助到了你,欢迎[点赞、收藏、关注]哦~
目录
这个问题真的找了我好久,但说起来其实也简单,就是GPU温度太高了。 问题复现视频演示:【踩坑】GPU运算使温度升高导致计算性能下降_哔哩哔哩_bilibili
1、运行监控指令:
nvidia-smi dmon -i 00000000:41:00.0 -s pucvmet --gpm-metrics 10
2、运行你的代码,等到出问题。
3、看图就知道,密集的GPU运算,导致GPU温度达到限制了。高温限制是会影响性能的。
本节内容来自:对于GPU显卡来说,多热算太热?
对于GPU来说,温度大致分为以下几个层次:
一般来说:
对GPU来说,长时间工作在85°C以上,会有以下影响:
所以总体来说,如果GPU显卡长期工作在85°C以上高温,会明显缩短GPU的平均使用寿命,从1-3年不等,同时也影响其锁定频率和稳定性能输出,建议尽量降低和控制工作温度。
这里是一些建议,可以帮助降低GPU的工作温度:
以上方法结合使用可以有效帮助控制GPU的工作温度,延长使用寿命。
GPU的降温挺快的,不调用GPU运算,它的温度就会开始降低,因此可以考虑适当的降低GPU的连续使用时间。
或者,可以在运行代码前,等待GPU的问题降低到一定的程度再执行。给个自己写的参考代码吧:
def check_gpu_temperatures(gpu_ids, temp_threshold=40, timeout=None):
gpu_ids_list = gpu_ids.split(',')
start_time = time.time()
while True:
temperatures = []
all_below_threshold = True
for gpu_id in gpu_ids_list:
result = subprocess.run(['nvidia-smi', '-i', gpu_id, '--query-gpu=temperature.gpu', '--format=csv,noheader,nounits'], stdout=subprocess.PIPE)
temp = int(result.stdout.decode('utf-8').strip())
temperatures.append(f'GPU {gpu_id}: {temp}°')
if temp > temp_threshold: all_below_threshold = False
if all_below_threshold:
print('>> 当前GPU温度: ' + ' | '.join(temperatures))
break
print(f'>> 为防止GPU高温导致性能限制,等待降温中({temp_threshold}°): ' + ' | '.join(temperatures), end='\r')
if timeout and (time.time() - start_time) > timeout:
print('\n已达超时,不在等待 GPU 温度下降。')
break
time.sleep(1)
print()
用法:
gpus = '2,3,4'
check_gpu_temperatures(gpu_ids=gpus , temp_threshold=60, timeout=None)
效果:
为了方便监控GPU的温度:
import sys
import subprocess
import threading
import time
import numpy as np
import tkinter as tk
from tkinter import ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
class RealtimePlot:
def __init__(self, parent, title, ylabel):
self.fig = Figure(figsize=(5, 2), dpi=100) # 设定图像尺寸
self.ax = self.fig.add_subplot(111)
self.ax.set_title(title)
self.ax.set_ylabel(ylabel)
self.ax.set_xlabel('Time')
self.xdata = []
self.ydata = []
self.line, = self.ax.plot(self.xdata, self.ydata, 'r-')
self.canvas = FigureCanvasTkAgg(self.fig, master=parent)
self.canvas.draw()
self.canvas.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
def update_plot(self, y):
self.xdata.append(time.time())
self.ydata.append(y)
if len(self.xdata) == 1: # 防止 transformation singular 错误
self.ax.set_xlim(self.xdata[0], self.xdata[0] + 1)
else:
self.ax.set_xlim(self.xdata[0], self.xdata[-1])
self.line.set_xdata(self.xdata)
self.line.set_ydata(self.ydata)
self.ax.relim()
self.ax.autoscale_view()
self.canvas.draw()
def resize(self, event):
self.fig.set_size_inches(event.width / self.canvas.get_tk_widget().winfo_fpixels('1i'),
event.height / self.canvas.get_tk_widget().winfo_fpixels('1i'))
self.canvas.draw()
class GPU_MonitorApp:
def __init__(self, root):
self.root = root
self.root.title("nvidia-smi dmon Realtime Plot")
self.plots = []
gpu_ids = ['00000000:3d:00.0', '00000000:3e:00.0', '00000000:1D:00.0', '00000000:1E:00.0', '00000000:41:00.0']
main_frame = tk.Frame(root)
main_frame.pack(fill=tk.BOTH, expand=1)
canvas = tk.Canvas(main_frame)
canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
scrollbar_y = tk.Scrollbar(main_frame, orient=tk.VERTICAL, command=canvas.yview)
scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)
scrollbar_x = tk.Scrollbar(root, orient=tk.HORIZONTAL, command=canvas.xview)
scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)
canvas.configure(yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set)
canvas.bind('<Configure>', lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
second_frame = tk.Frame(canvas)
canvas.create_window((0, 0), window=second_frame, anchor="nw")
plot_width = 500 # 每个图的宽度(以像素为单位)
plot_height = 200 # 每个图的高度(以像素为单位)
for i, gpu_id in enumerate(gpu_ids):
frame = ttk.Frame(second_frame, width=plot_width * 2, height=plot_height)
frame.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
plot_power = RealtimePlot(frame, f"GPU {i} Power Usage", "Power (W)")
plot_temp = RealtimePlot(frame, f"GPU {i} Temperature", "Temperature (C)")
self.plots.append((plot_power, plot_temp))
frame.bind("<Configure>", plot_power.resize)
frame.bind("<Configure>", plot_temp.resize)
# 计算窗口初始尺寸
window_width = plot_width * 2 + 40 # 两个图表并排 + 滚动条和边距
window_height = plot_height * len(gpu_ids) + 40 # 每个GPU占一行 + 滚动条和边距
self.root.geometry(f"{window_width}x{window_height}")
self.start_monitoring(gpu_ids)
def start_monitoring(self, gpu_ids):
self.monitor_thread = threading.Thread(target=self.monitor_gpu, args=(gpu_ids,))
self.monitor_thread.daemon = True
self.monitor_thread.start()
def monitor_gpu(self, gpu_ids):
command = ['nvidia-smi', 'dmon', '-i', ','.join(gpu_ids), '-s', 'pm']
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
skip_header = True # 用于跳过表头
for line in process.stdout:
try:
if skip_header:
if line.startswith('#'):
continue # 跳过表头行
skip_header = False
parts = line.split()
if len(parts) == 0 or parts[0] == '#':
continue # 跳过表头或空行
if len(parts) >= 7 and parts[0].isdigit(): # 确保行数据完整
gpu_idx = int(parts[0])
if gpu_idx < len(gpu_ids):
gpu_power = float(parts[1]) if parts[1] != '-' else None
gpu_temp = float(parts[2]) if parts[2] != '-' else None
print(f"GPU {gpu_idx} power: {gpu_power}, temp: {gpu_temp}") # Debug info
if gpu_power is not None:
self.plots[gpu_idx][0].update_plot(gpu_power)
if gpu_temp is not None:
self.plots[gpu_idx][1].update_plot(gpu_temp)
except Exception as e:
print(f"Error parsing line: {line}\n{e}")
if __name__ == '__main__':
root = tk.Tk()
app = GPU_MonitorApp(root)
root.mainloop()
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。