pycoze 0.1.16__py3-none-any.whl → 0.1.18__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pycoze/gpu/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .gpu_reserve import gpu
@@ -0,0 +1,167 @@
1
+ import subprocess
2
+ import sqlite3
3
+ import atexit
4
+ import time
5
+ import os
6
+ import psutil
7
+
8
+ try:
9
+ from pycoze.utils import utils
10
+
11
+ # 定义数据库连接和初始化
12
+ params = utils.arg.read_params()
13
+ if params:
14
+ DATABASE_PATH = params["appPath"] + "/gpu_usage.db"
15
+ else:
16
+ raise Exception("No params")
17
+ except:
18
+ DATABASE_DIR = os.path.expanduser("~/pycoze")
19
+ os.makedirs(DATABASE_DIR, exist_ok=True)
20
+ DATABASE_PATH = os.path.join(DATABASE_DIR, "gpu_usage.db")
21
+ TABLE_NAME = "gpu_usage"
22
+
23
+
24
+ def initialize_db():
25
+ conn = sqlite3.connect(DATABASE_PATH)
26
+ cursor = conn.cursor()
27
+ cursor.execute(
28
+ f"""
29
+ CREATE TABLE IF NOT EXISTS {TABLE_NAME} (
30
+ id INTEGER PRIMARY KEY,
31
+ process_id TEXT NOT NULL,
32
+ reserved_gb REAL NOT NULL
33
+ )
34
+ """
35
+ )
36
+ conn.commit()
37
+ conn.close()
38
+
39
+
40
+ # 检测GPU资源
41
+ def get_gpu_resources():
42
+ try:
43
+ # 使用nvidia-smi命令获取GPU信息
44
+ result = subprocess.run(
45
+ ["nvidia-smi", "--query-gpu=memory.free", "--format=csv,noheader,nounits"],
46
+ stdout=subprocess.PIPE,
47
+ text=True,
48
+ )
49
+ free_memory = result.stdout.strip().split("\n")
50
+ total_free_memory = sum(float(mem) for mem in free_memory)
51
+
52
+ # 获取正在使用GPU的进程信息
53
+ process_result = subprocess.run(
54
+ [
55
+ "nvidia-smi",
56
+ "--query-compute-apps=pid,process_name,used_memory",
57
+ "--format=csv,noheader,nounits",
58
+ ],
59
+ stdout=subprocess.PIPE,
60
+ text=True,
61
+ )
62
+ process_info = process_result.stdout.strip().split("\n")
63
+
64
+ # 过滤掉进程名中包含"python"的进程
65
+ python_memory_usage = 0.0
66
+ for process in process_info:
67
+ pid, process_name, used_memory = process.split(", ")
68
+ if "python" in process_name.lower():
69
+ python_memory_usage += float(used_memory)
70
+
71
+ # 计算排除python进程后的总空闲内存
72
+ total_free_memory -= python_memory_usage
73
+ return round(total_free_memory / 1024, 2)
74
+ except Exception as e:
75
+ print(f"Error getting GPU resources: {e}")
76
+ return 0.0
77
+
78
+
79
+ # 预留GPU资源
80
+ def reserve_gpu(gb):
81
+ process_id = str(os.getpid())
82
+ with sqlite3.connect(DATABASE_PATH) as conn:
83
+ cursor = conn.cursor()
84
+ cursor.execute(f"SELECT SUM(reserved_gb) FROM {TABLE_NAME}")
85
+ total_reserved = cursor.fetchone()[0]
86
+ if total_reserved is None:
87
+ total_reserved = 0.0
88
+ available_gb = get_gpu_resources() - total_reserved
89
+ if available_gb >= gb:
90
+ cursor.execute(
91
+ f"INSERT INTO {TABLE_NAME} (process_id, reserved_gb) VALUES (?, ?)",
92
+ (process_id, gb),
93
+ )
94
+ conn.commit()
95
+ print(f"预留成功,剩余GPU大小: {available_gb - gb} GB")
96
+ return True
97
+ else:
98
+ print(f"预留失败,剩余GPU大小: {available_gb} GB")
99
+ return False
100
+
101
+
102
+ def reserve_gpu_retry(gb, retry=10000):
103
+ for i in range(retry):
104
+ time.sleep(1)
105
+ if reserve_gpu(gb):
106
+ if i % 10 == 0 or i < 10:
107
+ print(f"重试第{i}次")
108
+ return True
109
+ return False
110
+
111
+
112
+ # 释放GPU资源
113
+ def release_gpu():
114
+ process_id = str(os.getpid())
115
+ with sqlite3.connect(DATABASE_PATH) as conn:
116
+ cursor = conn.cursor()
117
+ cursor.execute(f"DELETE FROM {TABLE_NAME} WHERE process_id = ?", (process_id,))
118
+ conn.commit()
119
+ # 计算释放后的剩余GPU大小
120
+ cursor.execute(f"SELECT SUM(reserved_gb) FROM {TABLE_NAME}")
121
+ total_reserved = cursor.fetchone()[0]
122
+ if total_reserved is None:
123
+ total_reserved = 0.0
124
+ available_gb = get_gpu_resources() - total_reserved
125
+ print(f"释放成功,剩余GPU大小: {available_gb} GB")
126
+
127
+
128
+ # 注册退出时的清理函数
129
+ def cleanup():
130
+ release_gpu()
131
+ print("程序退出,GPU资源已释放")
132
+
133
+
134
+ def initialize_and_check():
135
+ initialize_db()
136
+ with sqlite3.connect(DATABASE_PATH) as conn:
137
+ cursor = conn.cursor()
138
+ cursor.execute(f"SELECT process_id, reserved_gb FROM {TABLE_NAME}")
139
+ rows = cursor.fetchall()
140
+ for row in rows:
141
+ process_id, reserved_gb = row
142
+ try:
143
+ # 检查进程是否存在
144
+ psutil.Process(int(process_id))
145
+ except psutil.NoSuchProcess:
146
+ # 进程不存在,删除对应的记录
147
+ cursor.execute(
148
+ f"DELETE FROM {TABLE_NAME} WHERE process_id = ?", (process_id,)
149
+ )
150
+ print(f"进程 {process_id} 不存在,已删除对应的预留记录")
151
+ conn.commit()
152
+
153
+
154
+ # 在模块加载时执行初始化检查
155
+ initialize_and_check()
156
+
157
+ # 注册清理函数
158
+ atexit.register(cleanup)
159
+
160
+ if __name__ == "__main__":
161
+ if reserve_gpu_retry(10):
162
+ print("GPU资源预留成功")
163
+ time.sleep(100)
164
+ release_gpu()
165
+ print("GPU资源释放成功")
166
+ else:
167
+ print("GPU资源不足,无法预留")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pycoze
3
- Version: 0.1.16
3
+ Version: 0.1.18
4
4
  Summary: Package for pycoze only!
5
5
  Author: Yuan Jie Xiong
6
6
  Author-email: aiqqqqqqq@qq.com
@@ -11,6 +11,8 @@ pycoze/bot/agent/agent_types/__init__.py,sha256=PoYsSeQld0kdROjejN3BNjC9NsgKNekj
11
11
  pycoze/bot/agent/agent_types/openai_func_call_agent.py,sha256=YkpiMxrLl7aMYZJsOtZraTT2UE0IZrQsfikGRCHx4jM,4467
12
12
  pycoze/bot/agent/agent_types/react_agent.py,sha256=xgS6NFBtWUOrXQrJ1hq060VoTRsTj4Y_3gI1Sy3bEsU,6748
13
13
  pycoze/bot/agent/agent_types/react_prompt.py,sha256=PdzL3SFb0Ee0dbK4HGqG09bRISrru4bhOj45CXBtqI0,1919
14
+ pycoze/gpu/__init__.py,sha256=Oiydje7Y8347kG45ElKz3IlS_u2gWVgWcfSOK6AeZSc,29
15
+ pycoze/gpu/gpu_reserve.py,sha256=eKEnULikr1mKfqLeAZz3FdlWvJMdoUvqmCqx0K8eW4c,5141
14
16
  pycoze/ui/__init__.py,sha256=OLPOfXhWGlMVImUhpsOzhs4Jmhrg73lPSUMTTdA7q0I,181
15
17
  pycoze/ui/base.py,sha256=nXNXRTZ5Tl1AQp5nfjzLvOVzt_1nLSCn2IOyfxAN_fc,1471
16
18
  pycoze/ui/color.py,sha256=cT9Ib8uNzkOKxyW0IwVj46o4LwdB1xgNCj1_Rou9d_4,854
@@ -18,8 +20,8 @@ pycoze/ui/typ.py,sha256=NpT0FrbHvByOszBZMFtroRp7I7pN-38tYz_zPOPejF4,1723
18
20
  pycoze/ui/ui_def.py,sha256=Tsdc4sCxQZRQaN_hLmci8wcBrel999uZBgFaOSRnGn0,3701
19
21
  pycoze/utils/__init__.py,sha256=GMP9EhOsbRM0EfIzS2ll1fXKKSpY3zqpqkm66fPGBaM,39
20
22
  pycoze/utils/arg.py,sha256=VKinJRPiNw0TPvuRFwLg0Vz8u8HXx_ejGfOojfE9b_Y,706
21
- pycoze-0.1.16.dist-info/LICENSE,sha256=QStd_Qsd0-kAam_-sOesCIp_uKrGWeoKwt9M49NVkNU,1090
22
- pycoze-0.1.16.dist-info/METADATA,sha256=DmRaOWoSIrHN7Y6_4OCTrMH4OO4mPi-vF46tPPjiIiA,719
23
- pycoze-0.1.16.dist-info/WHEEL,sha256=UvcQYKBHoFqaQd6LKyqHw9fxEolWLQnlzP0h_LgJAfI,91
24
- pycoze-0.1.16.dist-info/top_level.txt,sha256=76dPeDhKvOCleL3ZC5gl1-y4vdS1tT_U1hxWVAn7sFo,7
25
- pycoze-0.1.16.dist-info/RECORD,,
23
+ pycoze-0.1.18.dist-info/LICENSE,sha256=QStd_Qsd0-kAam_-sOesCIp_uKrGWeoKwt9M49NVkNU,1090
24
+ pycoze-0.1.18.dist-info/METADATA,sha256=WyNhtFDyWF5zgdPPmwzJWMaU7qoLDFc1ptCrL9TmNx0,719
25
+ pycoze-0.1.18.dist-info/WHEEL,sha256=UvcQYKBHoFqaQd6LKyqHw9fxEolWLQnlzP0h_LgJAfI,91
26
+ pycoze-0.1.18.dist-info/top_level.txt,sha256=76dPeDhKvOCleL3ZC5gl1-y4vdS1tT_U1hxWVAn7sFo,7
27
+ pycoze-0.1.18.dist-info/RECORD,,