-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunpod_interface.py
More file actions
391 lines (336 loc) Β· 16.6 KB
/
Copy pathrunpod_interface.py
File metadata and controls
391 lines (336 loc) Β· 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import subprocess
import time
import requests
import sys
import re
try:
from config import GPU_TIERS, MODEL_SPECIFIC_TIERS, KEYWORD_TIERS
except ImportError:
# Fallback if config is missing (for safety)
GPU_TIERS, MODEL_SPECIFIC_TIERS, KEYWORD_TIERS = {}, {}, []
class RunPodDriver:
def __init__(self, api_key, pod_id):
self.api_key = api_key
self.pod_id = pod_id
self.new_pod_id = None
self.current_gpu_type = None
self.pod_cost = 0.0
def _run_cmd(self, cmd_list):
"""Executes shell commands via subprocess."""
try:
# On Windows, shell=False with a list of args is usually safest for runpodctl
result = subprocess.run(cmd_list, capture_output=True, text=True, check=True)
return result.stdout
except subprocess.CalledProcessError as e:
return f"ERROR: {e.stderr}"
def get_balance(self):
"""Fetches RunPod balance via GraphQL."""
query = "query { myself { balance } }"
try:
resp = requests.post(
f"https://api.runpod.io/graphql?api_key={self.api_key}",
json={'query': query}, timeout=5
)
# print(f"[DEBUG] Balance Resp: {resp.status_code} | {resp.text}")
if resp.status_code == 200:
data = resp.json()
if 'errors' in data:
print(f"\n[PHOENIX] β οΈ Balance Error: {data['errors'][0]['message']}")
return 0.0
return data['data']['myself']['balance']
except Exception as e:
print(f"\n[PHOENIX] β οΈ Balance Fetch Failed: {e}")
return 0.0
def _refresh_cost(self):
"""Updates pod_cost based on current_gpu_type."""
if self.current_gpu_type:
avail = self.get_available_gpus()
# print(f"[DEBUG] Refreshing Cost for {self.current_gpu_type}. Found {len(avail)} GPUs.")
for g in avail:
if g['name'] == self.current_gpu_type:
self.pod_cost = g['price']
# print(f"[DEBUG] Found Price: ${self.pod_cost}")
break
else:
# Fallback: Scrape exact string match failed, try partial?
pass
def get_available_gpus(self):
"""Scrapes cloud stock and pricing."""
output = self._run_cmd(["runpodctl", "get", "cloud"])
# print(f"[DEBUG] Cloud Raw: {output[:100]}...") # Peek
lines = output.strip().split('\n')
gpus = []
# Regex to capture: Name, VRAM (int), Price (float)
# Expected format: "1x NVIDIA A40 48 GB 0.34"
regex = r'^(1x\s.*?)\s+(\d+)\s*GB\s+([\d\.]+)$'
for line in lines:
match = re.search(regex, line)
if match:
name = match.group(1).replace('1x ', '').strip()
vram = int(match.group(2))
price = float(match.group(3))
gpus.append({"name": name, "vram": vram, "price": price})
return gpus
def create_pod_on_gpu(self, gpu_type, target_model):
"""Rents GPU with verified Image and Token handling."""
print(f"[PHOENIX] π£ Renting {gpu_type}...")
# 1. Clean Command (No quotes, no 'vllm serve')
start_cmd = (
"/bin/sh -c \""
"pip install --upgrade pip --cache-dir /root/.cache/huggingface/pip_cache && "
"pip install vllm transformers --cache-dir /root/.cache/huggingface/pip_cache && "
"python3 -m vllm.entrypoints.openai.api_server "
f"--model {target_model} "
"--gpu-memory-utilization 0.95 "
"--max-model-len 8192 "
"--dtype auto "
"--trust-remote-code "
"--disable-frontend-multiprocessing " # Fix for Engine Core Init failures
)
# Auto-detect AWQ
if "awq" in target_model.lower() or "4bit" in target_model.lower():
start_cmd += " --quantization awq"
start_cmd += " || sleep infinity\""
args = [
"runpodctl", "create", "pod",
"--name", "VoxAI_Cloud",
"--imageName", "runpod/pytorch:2.2.0-py3.10-cuda12.1.1-devel-ubuntu22.04",
"--gpuType", gpu_type,
"--volumeSize", "100",
"--volumePath", "/root/.cache/huggingface",
"--ports", "8000/http",
"--env", "HF_TOKEN=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",
"--env", f"MODEL={target_model}",
"--args", start_cmd
]
output = self._run_cmd(args)
# print(f"[DEBUG] Raw RunPod Output: {output}") # Reduce noise
pod_id = None
if "created" in output.lower():
import re
match = re.search(r'pod\s+"([^"]+)"\s+created', output.lower())
if match: pod_id = match.group(1)
else:
match = re.search(r'"([a-zA-Z0-9-]+)"', output)
if match: pod_id = match.group(1)
if pod_id:
self.current_gpu_type = gpu_type
# Try to update cost if possible, or do it later
# For now, we set it to 0 and let switch_model update it or get_balace
# Actually, to get cost, we need to know the price of the GPU we just rented.
# We can lookup from available GPUs or just assume the user saw it.
# Let's try to find it in get_available_gpus if available.
avail = self.get_available_gpus()
for g in avail:
if g['name'] == gpu_type:
self.pod_cost = g['price']
break
return pod_id
return None
def restart_server(self, target_model):
"""Hot-swaps the model inside the existing pod."""
print(f"[PHOENIX] β»οΈ Optimizing: Reusing active GPU ({self.current_gpu_type})...")
self._refresh_cost() # Ensure we have the price
active_id = self.new_pod_id if self.new_pod_id else self.pod_id
# 1. Kill existing vLLM
print("[PHOENIX] π Stopping current model...")
self._run_cmd(["runpodctl", "exec", "pod", active_id, "--", "pkill -f vllm"])
# 2. Wait for Death (Crucial!)
print("[PHOENIX] π Verifying shutdown...")
url = f"https://{active_id}-8000.proxy.runpod.net/v1/models"
for _ in range(15):
try:
requests.get(url, timeout=2) # If this succeeds, it's still alive
time.sleep(1)
except:
break # Connection failed = Logic Success (Server is dead)
else:
# Force Kill if pkill failed
self._run_cmd(["runpodctl", "exec", "pod", active_id, "--", "killall -9 python3"])
# 2. Start new vLLM (Background)
print(f"[PHOENIX] π Starting {target_model}...")
# Use nohup to keep it running after exec returns
start_cmd = (
f"nohup python3 -m vllm.entrypoints.openai.api_server "
f"--model {target_model} "
"--gpu-memory-utilization 0.95 "
"--max-model-len 8192 "
"--dtype auto "
"--trust-remote-code "
"--disable-frontend-multiprocessing "
)
# Auto-detect AWQ
if "awq" in target_model.lower() or "4bit" in target_model.lower():
start_cmd += " --quantization awq"
start_cmd += " > /var/log/vllm.log 2>&1 &"
self._run_cmd(["runpodctl", "exec", "pod", active_id, "--", "bash", "-c", start_cmd])
return True
def _get_model_tier(self, target_model):
"""Resolves the required GPU Tier for a model."""
if target_model in MODEL_SPECIFIC_TIERS:
return MODEL_SPECIFIC_TIERS[target_model]
for keywords, tier_name in KEYWORD_TIERS:
for kw in keywords:
if kw == "*" or kw.lower() in target_model.lower():
return tier_name
return "tier_standard"
def _get_gpu_tier(self, gpu_name):
"""Identifies which tier the current GPU belongs to."""
if not gpu_name: return None
for tier, gpus in GPU_TIERS.items():
if gpu_name in gpus:
return tier
return None
def switch_model(self, target_model):
"""Priority: Defined List -> Scrape 48GB+ -> User Pick -> Retry 3x."""
print(f"\n[PHOENIX] π₯ Initiating Swap...")
active_id = self.new_pod_id if self.new_pod_id else self.pod_id
# Resolve Tiers
target_tier = self._get_model_tier(target_model)
current_tier = self._get_gpu_tier(self.current_gpu_type)
print(f"[PHOENIX] π Swap Analysis: Target={target_tier} | Current={current_tier} ({self.current_gpu_type})")
# --- PHASE 1: Try In-Pod Swap (Reuse) ---
can_reuse = False
if active_id and current_tier:
if current_tier == target_tier: can_reuse = True
elif current_tier == "tier_ultra" and target_tier == "tier_standard": can_reuse = True
if can_reuse:
if self.restart_server(target_model):
if self.wait_for_boot(target_model, is_swap=True):
return True
else:
print("[PHOENIX] β οΈ In-Pod Swap failed (Container likely reset). Retrying with fresh pod...")
# --- PHASE 2: Terminate Old Pod ---
if active_id:
print(f"[PHOENIX] β οΈ Terminating old pod {active_id}...")
self._run_cmd(["runpodctl", "remove", "pod", active_id])
time.sleep(2)
# --- PHASE 3: Automatic Priority List ---
# 3.1 Tier Selection
selected_tier = None
# A. Check Specific Model ID (High Priority)
if target_model in MODEL_SPECIFIC_TIERS:
selected_tier = MODEL_SPECIFIC_TIERS[target_model]
print(f"[PHOENIX] π― Exact Match: '{target_model}' -> {selected_tier}")
# B. Check Keywords (Fallback)
if not selected_tier:
for keywords, tier_name in KEYWORD_TIERS:
for kw in keywords:
if kw == "*" or kw.lower() in target_model.lower():
selected_tier = tier_name
print(f"[PHOENIX] π Keyword Match: '{kw}' -> {selected_tier}")
break
if selected_tier: break
# 3.2 Resolve GPU List
priority_list = GPU_TIERS.get(selected_tier, [])
# Hardcoded fallback just in case config is weird
if not priority_list:
print("[PHOENIX] β οΈ No Tier matched, using safe fallback.")
priority_list = ["NVIDIA A40", "NVIDIA RTX A6000"]
print(f"[PHOENIX] π΅οΈ Checking Priority List: {priority_list}")
for gpu in priority_list:
new_id = self.create_pod_on_gpu(gpu, target_model)
if new_id:
self.new_pod_id = new_id
print(f"[PHOENIX] β
Successfully secured {gpu}.")
return self.wait_for_boot(target_model)
# print(f"[PHOENIX] β οΈ {gpu} unavailable...")
# --- PHASE 4: Manual Selection from Available 48GB+ ---
print("\n[PHOENIX] β οΈ Priority GPUs unavailable. Scanning cloud for options...")
all_gpus = self.get_available_gpus()
# Filter for >= 48GB (or >= 24GB if desperate? User said sorted from 48GB and up)
# Let's show everything 24GB+ just in case, but sort by VRAM desc
candidates = [g for g in all_gpus if g['vram'] >= 24]
candidates.sort(key=lambda x: (-x['vram'], x['price']))
if not candidates:
print("[PHOENIX] β No High-VRAM GPUs available.")
return False
print("\n=== βοΈ Available High-VRAM GPUs ===")
print(f"{'#':<3} {'GPU Name':<25} {'VRAM':<8} {'Price/Hr':<10}")
print("-" * 50)
for i, g in enumerate(candidates):
print(f"{i+1:<3} {g['name']:<25} {g['vram']}GB ${g['price']:.2f}")
try:
choice_idx = int(input("\nSelect GPU # (0 to cancel): ")) - 1
if choice_idx < 0: return False
selected_gpu_name = candidates[choice_idx]['name']
# --- PHASE 5: Retry Loop (3x) ---
print(f"[PHOENIX] π― Targeting: {selected_gpu_name}. Attempting to rent (Max 3 retries)...")
for attempt in range(3):
new_id = self.create_pod_on_gpu(selected_gpu_name, target_model)
if new_id:
self.new_pod_id = new_id
print(f"[PHOENIX] β
Successfully secured {selected_gpu_name}.")
return self.wait_for_boot(target_model)
print(f"[PHOENIX] β οΈ Attempt {attempt+1}/3 failed. Retrying in 2s...")
time.sleep(2)
print("[PHOENIX] β Failed to rent selected GPU after 3 attempts.")
return False
except: return False
def wait_for_boot(self, target_model, is_swap=False):
"""Monitors boot status and verifies the pod actually exists."""
print(f"[PHOENIX] β³ Waiting for Engine...")
mismatch_count = 0
max_mismatch = 5 if is_swap else 20 # Fail faster on swaps
# Wait up to 10 mins (600s) because large models take time to download/load
for i in range(100):
# 1. Verify Pod Exists
pod_list = self._run_cmd(["runpodctl", "get", "pod"])
if self.new_pod_id not in pod_list:
print(f"\n[PHOENIX] β CRITICAL: Pod {self.new_pod_id} disappeared from server!")
print("[PHOENIX] This usually means it crashed on boot (Driver/Backend mismatch).")
return False
# 2. Check HTTP Endpoint AND Model ID
try:
url = f"https://{self.new_pod_id}-8000.proxy.runpod.net/v1/models"
resp = requests.get(url, timeout=3)
if resp.status_code == 200:
data = resp.json()
# Check if the LOADED model matches the TARGET model
# This prevents connecting to the OLD server process if it refused to die
if 'data' in data and len(data['data']) > 0:
loaded_id = data['data'][0]['id']
# Flexible matching (case-insensitive for safety)
if target_model.lower() in loaded_id.lower() or loaded_id.lower() in target_model.lower():
print(f"\n[PHOENIX] β
Online! Serving: {loaded_id}")
return True
else:
mismatch_count += 1
print(f"\n[DEBUG] Valid Endpoint, but ID mismatch ({mismatch_count}/{max_mismatch}): '{loaded_id}' != '{target_model}'")
if mismatch_count >= max_mismatch:
print(f"[PHOENIX] β Swap Verification Failed: Persistent Old Model Detected.")
return False
except:
pass
# 3. Stream Logs
self.stream_container_logs(self.new_pod_id)
sys.stdout.write(f"\r[PHOENIX] β³ Booting... ({i*6}s)")
sys.stdout.flush()
time.sleep(6)
print("\n[PHOENIX] β Boot Timed Out.")
return False
print("\n[PHOENIX] β Boot Timed Out.")
return False
def stream_container_logs(self, pod_id):
"""Fetches and displays new logs from the container."""
try:
output = self._run_cmd(["runpodctl", "logs", "pod", pod_id, "--tail", "5"])
if output and "ERROR" not in output:
lines = output.strip().split('\n')
for line in lines:
# Simple de-duplication could be added here if needed
# For now, just printing the tail gives a sense of activity
if line.strip():
print(f"\n[POD LOG] {line.strip()}")
except: pass
def terminate_pod(self):
"""Terminates the active pod to save costs."""
pod_id = self.new_pod_id if self.new_pod_id else self.pod_id
if pod_id:
print(f"\n[PHOENIX] β οΈ Terminating pod {pod_id}...")
self._run_cmd(["runpodctl", "remove", "pod", pod_id])
self.new_pod_id = None
self.pod_id = None
print(f"[PHOENIX] β
Pod terminated successfully.")
else:
print("\n[PHOENIX] No active pod to terminate.")