iroiro_data / Tools /gpu_pl_keeper /gpu_pl_keeper_v2.py
mokyu2106's picture
Upload 3 files
7f6423f verified
Raw
History Blame Contribute Delete
7.32 kB
import subprocess
import tkinter as tk
from tkinter import messagebox
from datetime import datetime
from pathlib import Path
# =========================
# GPU PL Keeper Ver2
# =========================
GPU_INDEX = 0
CHECK_INTERVAL_SEC = 60
CHECK_INTERVAL_MS = CHECK_INTERVAL_SEC * 1000
# RTX5090の70%相当。5090環境では 575W * 70% = 402.5W 付近。
# ThunderMasterで70%にした時の nvidia-smi 表示に合わせて必要なら 400 / 402 / 403 などに調整してください。
DEFAULT_TARGET_PL_W = 402
LOG_FILE = Path(__file__).with_name("gpu_pl_keeper.log")
def run_cmd(cmd: list[str]) -> str:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return subprocess.check_output(
cmd,
text=True,
stderr=subprocess.STDOUT,
startupinfo=startupinfo
).strip()
def get_current_pl() -> float:
cmd = [
"nvidia-smi",
"-i", str(GPU_INDEX),
"--query-gpu=power.limit",
"--format=csv,noheader,nounits"
]
return float(run_cmd(cmd))
def set_power_limit(watts: float) -> str:
cmd = [
"nvidia-smi",
"-i", str(GPU_INDEX),
"-pl", str(int(round(watts)))
]
return run_cmd(cmd)
def is_admin_error(error_text: str) -> bool:
return "Insufficient Permissions" in error_text or "permission" in error_text.lower()
class GPUPlKeeperApp:
def __init__(self, root: tk.Tk):
self.root = root
self.root.title("GPU PL Keeper Ver2")
self.root.geometry("420x330")
self.root.resizable(True, True)
self.running = False
self.after_id = None
self.last_fixed_at = "-"
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
title = tk.Label(root, text="GPU PL Keeper Ver2", font=("Meiryo", 14, "bold"))
title.pack(pady=(10, 4))
frame = tk.Frame(root)
frame.pack(pady=4)
tk.Label(frame, text="目標PL(W):", font=("Meiryo", 10)).grid(row=0, column=0, padx=4)
self.target_entry = tk.Entry(frame, width=10, justify="center")
self.target_entry.insert(0, str(DEFAULT_TARGET_PL_W))
self.target_entry.grid(row=0, column=1, padx=4)
self.status_label = tk.Label(
root,
text="停止中",
font=("Meiryo", 11, "bold"),
bg="#dddddd",
width=34
)
self.status_label.pack(pady=8)
self.current_label = tk.Label(root, text="現在PL: 未取得", font=("Meiryo", 10))
self.current_label.pack()
self.fixed_label = tk.Label(root, text="最終修正: -", font=("Meiryo", 10))
self.fixed_label.pack(pady=(0, 6))
button_frame = tk.Frame(root)
button_frame.pack(pady=4)
self.start_button = tk.Button(button_frame, text="監視開始", width=10, command=self.start)
self.start_button.grid(row=0, column=0, padx=4)
self.stop_button = tk.Button(button_frame, text="監視停止", width=10, command=self.stop)
self.stop_button.grid(row=0, column=1, padx=4)
self.check_button = tk.Button(button_frame, text="今すぐ確認", width=12, command=self.check_once_manual)
self.check_button.grid(row=0, column=2, padx=4)
self.log = tk.Text(root, height=10, font=("Consolas", 9))
self.log.pack(fill="both", expand=True, padx=8, pady=8)
self.write_log("起動しました。管理者権限での実行を推奨します。")
self.write_log(f"監視間隔: {CHECK_INTERVAL_SEC}秒")
def write_log(self, text: str):
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"[{now}] {text}"
self.log.insert("end", line + "\n")
self.log.see("end")
try:
with LOG_FILE.open("a", encoding="utf-8") as f:
f.write(line + "\n")
except Exception:
pass
def set_status(self, text: str, color: str):
self.status_label.config(text=text, bg=color)
def get_target_pl(self) -> float:
raw = self.target_entry.get().strip()
if not raw:
raise ValueError("目標PLが空です。")
return float(raw)
def start(self):
self.running = True
self.set_status("監視中", "#9fd3ff")
self.write_log("監視を開始しました。")
self.check_pl()
def stop(self):
self.running = False
if self.after_id is not None:
try:
self.root.after_cancel(self.after_id)
except Exception:
pass
self.after_id = None
self.set_status("停止中", "#dddddd")
self.write_log("監視を停止しました。")
def check_once_manual(self):
self.check_pl(schedule_next=False)
def check_pl(self, schedule_next=True):
try:
target_pl = self.get_target_pl()
current_pl = get_current_pl()
self.current_label.config(text=f"現在PL: {current_pl:.0f} W")
# 1W以内は誤差扱い
if abs(current_pl - target_pl) <= 1:
self.set_status("正常", "#a8e6a1")
self.write_log(f"正常: 現在 {current_pl:.0f}W / 目標 {target_pl:.0f}W")
else:
self.set_status("不一致検出・修正中", "#ffe08a")
self.write_log(f"PL不一致: 現在 {current_pl:.0f}W / 目標 {target_pl:.0f}W")
result = set_power_limit(target_pl)
fixed_pl = get_current_pl()
self.current_label.config(text=f"現在PL: {fixed_pl:.0f} W")
self.last_fixed_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.fixed_label.config(text=f"最終修正: {self.last_fixed_at}")
if abs(fixed_pl - target_pl) <= 1:
self.set_status("修正完了", "#a8e6a1")
self.write_log(f"自動修正完了: {current_pl:.0f}W → {fixed_pl:.0f}W")
else:
self.set_status("修正後も不一致", "#ff9a9a")
self.write_log(f"警告: 修正後も不一致です。現在 {fixed_pl:.0f}W")
self.write_log(f"nvidia-smi出力: {result}")
except subprocess.CalledProcessError as e:
error_text = e.output.strip() if e.output else str(e)
self.set_status("エラー", "#ff9a9a")
self.write_log(f"コマンドエラー: {error_text}")
if is_admin_error(error_text):
messagebox.showwarning(
"管理者権限が必要です",
"PL変更に失敗しました。\n"
"このツールを管理者権限で起動してください。"
)
except Exception as e:
self.set_status("エラー", "#ff9a9a")
self.write_log(f"エラー: {e}")
finally:
if self.running and schedule_next:
self.after_id = self.root.after(CHECK_INTERVAL_MS, self.check_pl)
def on_close(self):
# ×で閉じると監視も終了します。
self.stop()
self.root.destroy()
if __name__ == "__main__":
root = tk.Tk()
app = GPUPlKeeperApp(root)
root.mainloop()