Skip to content

PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度

Update RunPod management to the V2 API. (#2271)

Sun, Xuehao323e48d47052
diff --git a/.azure-pipelines/nightly-test-cuda.yml b/.azure-pipelines/nightly-test-cuda.yml
index 691beccc8..d3b609792 100644
--- a/.azure-pipelines/nightly-test-cuda.yml
+++ b/.azure-pipelines/nightly-test-cuda.yml
@@ -72,15 +72,12 @@ stages:
inputs:
targetType: "inline"
script: |
- CUDA_VERSION="13.0"
-
python .azure-pipelines/scripts/cuda_unit_test/runpod_manager.py \
--action create \
--api_key $(RUNPOD_API_KEY) \
--name "nightly-$(Build.BuildId)" \
--container_disk_size "100" \
--part 0 \
- --cuda_version "${CUDA_VERSION}" \
--env AZP_URL=$(System.CollectionUri) AZP_TOKEN=$(AZP_DEVOPS_PAT) AZP_POOL=$(POOL_NAME) AZP_AGENT_NAME="$(AGENT_NAME)"
env:
PYTHONUNBUFFERED: '1'
diff --git a/.azure-pipelines/scripts/cuda_unit_test/monitor_gpu.py b/.azure-pipelines/scripts/cuda_unit_test/monitor_gpu.py
index 607c6b0b2..13b9f5d9a 100644
--- a/.azure-pipelines/scripts/cuda_unit_test/monitor_gpu.py
+++ b/.azure-pipelines/scripts/cuda_unit_test/monitor_gpu.py
@@ -6,6 +6,7 @@
# ]
# ///
+import csv
import math
import os
import sys
@@ -18,6 +19,27 @@ SIGNAL_FILE = "stop_monitor.flag"
DATA_FILE = "gpu_metrics.csv"
+def _to_float(value):
+ try:
+ parsed = float(value)
+ except (TypeError, ValueError):
+ return None
+
+ return parsed if math.isfinite(parsed) else None
+
+
+def _format_metric(value):
+ return "N/A" if value is None else f"{value:g}"
+
+
+def _convert_timestamps(timestamps_sec, max_sec):
+ if max_sec < 300:
+ return timestamps_sec
+ if max_sec < 7200:
+ return [round(timestamp / 60.0, 2) for timestamp in timestamps_sec]
+ return [round(timestamp / 3600.0, 2) for timestamp in timestamps_sec]
+
+
def run_daemon():
"""Background daemon: streams metrics to a local file in real time."""
if os.path.exists(SIGNAL_FILE):
@@ -28,10 +50,14 @@ def run_daemon():
print("GPU Monitor Daemon started.")
try:
- device = Device(0) # Monitor GPU 0; adjust if multiple GPUs are present
+ device = Device.cuda(0)
except Exception as e:
- print(f"NVML error: {e}")
- sys.exit(0)
+ print(f"CUDA-visible GPU lookup failed: {e}; falling back to NVML GPU 0.")
+ try:
+ device = Device(0)
+ except Exception as e:
+ print(f"NVML error: {e}")
+ sys.exit(0)
start_time = time.time()
print("Daemon is running. Streaming metrics to CSV every 5 seconds...")
@@ -42,15 +68,14 @@ def run_daemon():
while not os.path.exists(SIGNAL_FILE):
try:
elapsed_sec = int(time.time() - start_time)
- util = device.gpu_utilization()
- util_val = util if util is not None else 0
- mem_bytes = device.memory_used()
- mem_gb = round((mem_bytes / (1024**3)), 2) if mem_bytes is not None else 0.0
+ util_val = _to_float(device.gpu_utilization())
+ mem_bytes = _to_float(device.memory_used())
+ mem_gb = round((mem_bytes / (1024**3)), 2) if mem_bytes is not None else None
- f.write(f"{elapsed_sec},{util_val},{mem_gb}\n")
+ f.write(f"{elapsed_sec},{_format_metric(util_val)},{_format_metric(mem_gb)}\n")
f.flush()
- except Exception:
- pass
+ except Exception as e:
+ print(f"Failed to collect GPU metrics: {e}")
time.sleep(5.0)
@@ -69,34 +94,72 @@ def stop_and_plot():
sys.exit(1)
timestamps_sec = []
+ gpu_timestamps_sec = []
gpu_util = []
+ mem_timestamps_sec = []
mem_gb = []
+ invalid_rows = 0
+ missing_util_rows = 0
- with open(DATA_FILE, "r") as f:
- lines = f.readlines()[1:] # skip header
- for line in lines:
- parts = line.strip().split(",")
- if len(parts) == 3:
- timestamps_sec.append(int(parts[0]))
- gpu_util.append(int(parts[1]))
- mem_gb.append(float(parts[2]))
+ try:
+ with open(DATA_FILE, "r", newline="") as f:
+ reader = csv.reader(f)
+ next(reader, None)
+ for row_number, parts in enumerate(reader, start=2):
+ if len(parts) != 3:
+ invalid_rows += 1
+ print(f"Skipping malformed GPU metrics row {row_number}.")
+ continue
+
+ try:
+ timestamp = int(parts[0])
+ except (TypeError, ValueError):
+ invalid_rows += 1
+ print(f"Skipping GPU metrics row {row_number}: invalid timestamp {parts[0]!r}.")
+ continue
+
+ util_value = _to_float(parts[1])
+ mem_value = _to_float(parts[2])
+ if util_value is None:
+ missing_util_rows += 1
+ if util_value is None and mem_value is None:
+ invalid_rows += 1
+ print(f"Skipping GPU metrics row {row_number}: no numeric metrics.")
+ continue
+
+ timestamps_sec.append(timestamp)
+ if util_value is not None:
+ gpu_timestamps_sec.append(timestamp)
+ gpu_util.append(util_value)
+ if mem_value is not None:
+ mem_timestamps_sec.append(timestamp)
+ mem_gb.append(mem_value)
+ except (OSError, csv.Error) as e:
+ print(f"Failed to read GPU metrics data: {e}")
+ return
if not timestamps_sec:
print("No valid data to plot.")
return
+ if invalid_rows:
+ print(f"Skipped {invalid_rows} invalid GPU metrics row(s).")
+ if missing_util_rows:
+ print(f"GPU utilization was unavailable in {missing_util_rows} row(s); omitted from the utilization plot.")
+
# --- Dynamic time unit selection ---
max_sec = max(timestamps_sec) if timestamps_sec else 1
if max_sec < 300:
- x_data = timestamps_sec
x_label = "Time (Seconds)"
elif max_sec < 7200:
- x_data = [round(t / 60.0, 2) for t in timestamps_sec]
x_label = "Time (Minutes)"
else:
- x_data = [round(t / 3600.0, 2) for t in timestamps_sec]
x_label = "Time (Hours)"
+ x_data = _convert_timestamps(timestamps_sec, max_sec)
+ gpu_x_data = _convert_timestamps(gpu_timestamps_sec, max_sec)
+ mem_x_data = _convert_timestamps(mem_timestamps_sec, max_sec)
+
# --- Compute clean axis upper limits ---
SCALE = 11
@@ -111,49 +174,55 @@ def stop_and_plot():
# Nudge values that sit exactly on the axis limit slightly inward
# so plotille does not clip them at the canvas edge.
# ==========================================
- safe_x_data = [min(x, x_lim - 0.0001) for x in x_data]
- safe_gpu_util = gpu_util
+ safe_gpu_x_data = [min(x, x_lim - 0.0001) for x in gpu_x_data]
+ safe_mem_x_data = [min(x, x_lim - 0.0001) for x in mem_x_data]
safe_mem_gb = [min(m, y_lim_mem - 0.001) for m in mem_gb]
- print("\n" + "=" * 35 + " GPU Utilization (%) " + "=" * 35)
- try:
- print(
- plotille.plot(
- safe_x_data,
- safe_gpu_util,
- height=SCALE,
- width=80,
- X_label=x_label,
- Y_label="GPU Util (%)",
- x_min=0,
- x_max=x_lim,
- y_min=0,
- y_max=SCALE * 10,
- interp="linear",
+ if gpu_util:
+ print("\n" + "=" * 35 + " GPU Utilization (%) " + "=" * 35)
+ try:
+ print(
+ plotille.plot(
+ safe_gpu_x_data,
+ gpu_util,
+ height=SCALE,
+ width=80,
+ X_label=x_label,
+ Y_label="GPU Util (%)",
+ x_min=0,
+ x_max=x_lim,
+ y_min=0,
+ y_max=SCALE * 10,
+ interp="linear",
+ )
)
- )
- except Exception as e:
- print(f"Failed to plot GPU Utilization: {e}")
-
- print("\n" + "=" * 35 + " GPU Memory Used (GB) " + "=" * 35)
- try:
- print(
- plotille.plot(
- safe_x_data,
- safe_mem_gb,
- height=SCALE,
- width=80,
- X_label=x_label,
- Y_label="Memory (GB)",
- x_min=0,
- x_max=x_lim,
- y_min=0,
- y_max=y_lim_mem,
- interp="linear",
+ except Exception as e:
+ print(f"Failed to plot GPU Utilization: {e}")
+ else:
+ print("No valid GPU utilization data to plot.")
+
+ if mem_gb:
+ print("\n" + "=" * 35 + " GPU Memory Used (GB) " + "=" * 35)
+ try:
+ print(
+ plotille.plot(
+ safe_mem_x_data,
+ safe_mem_gb,
+ height=SCALE,
+ width=80,
+ X_label=x_label,
+ Y_label="Memory (GB)",
+ x_min=0,
+ x_max=x_lim,
+ y_min=0,
+ y_max=y_lim_mem,
+ interp="linear",
+ )
)
- )
- except Exception as e:
- print(f"Failed to plot GPU Memory: {e}")
+ except Exception as e:
+ print(f"Failed to plot GPU Memory: {e}")
+ else:
+ print("No valid GPU memory data to plot.")
if __name__ == "__main__":
diff --git a/.azure-pipelines/scripts/cuda_unit_test/runpod_manager.py b/.azure-pipelines/scripts/cuda_unit_test/runpod_manager.py
index 5e9ce69df..fa3bf7f0e 100644
--- a/.azure-pipelines/scripts/cuda_unit_test/runpod_manager.py
+++ b/.azure-pipelines/scripts/cuda_unit_test/runpod_manager.py
@@ -1,15 +1,23 @@
import argparse
import json
-import sys
import time
import requests
+V2_BASE_URL = "https://api.runpod.io/v2"
+REQUEST_TIMEOUT = 30
+RETRYABLE_STATUS_CODES = {429, 500, 501, 502, 503, 504}
+
TARGET_GPUS = [
"NVIDIA GeForce RTX 4090",
"NVIDIA GeForce RTX 5090",
+ "NVIDIA RTX PRO 4500 Blackwell Server Edition",
+ "NVIDIA RTX PRO 4500 Blackwell",
+ "NVIDIA RTX PRO 6000 Blackwell Server Edition MIG 1g.24gb",
+ "NVIDIA RTX PRO 4000 Blackwell",
"NVIDIA RTX 6000 Ada Generation",
"NVIDIA L40S",
+ "NVIDIA RTX PRO 6000 Blackwell Server Edition MIG 2g.48gb",
"NVIDIA RTX PRO 6000 Blackwell Server Edition",
"NVIDIA RTX PRO 6000 Blackwell Workstation Edition",
"NVIDIA L40",
@@ -17,181 +25,282 @@ TARGET_GPUS = [
"NVIDIA H100 80GB HBM3",
"NVIDIA H200",
]
-DATA_CENTER_IDS = [
- "AP-JP-1",
- "CA-MTL-1",
- "CA-MTL-2",
- "CA-MTL-3",
- "EU-CZ-1",
- "EU-FR-1",
- "EU-NL-1",
- "EU-RO-1",
- "EU-SE-1",
- "EUR-IS-1",
- "EUR-IS-2",
- "EUR-IS-3",
- "EUR-NO-1",
- "OC-AU-1",
- "US-CA-2",
- "US-DE-1",
- "US-GA-1",
- "US-GA-2",
- "US-IL-1",
- "US-KS-2",
- "US-KS-3",
- "US-NC-1",
- "US-TX-1",
- "US-TX-3",
- "US-TX-4",
- "US-WA-1",
-]
-DATA_CENTER_BAN_LIST = ["EUR-IS-1", "EUR-IS-2", "US-IL-1", "EU-CZ-1"]
-DATA_CENTER_SELECT_LIST = [dc for dc in DATA_CENTER_IDS if dc not in DATA_CENTER_BAN_LIST]
-REQUIRED_COUNT = 1
+DATA_CENTER_BAN_LIST = ["EUR-IS-1", "EUR-IS-2", "US-IL-1", "EU-CZ-1", "EUR-NO-1"]
CU130_IMAGES_NAME = "ghcr.io/xuehaosun/azure-agent:13.0"
-CUDA_VERSIONS = ["13.0"]
-
+MIN_CUDA_VERSION = "13.0"
-def run_create_pod(api_key, payload):
- url = "https://rest.runpod.io/v1/pods"
- headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
- max_retries = 3
- for attempt in range(max_retries + 1):
- response = requests.post(url, json=payload, headers=headers)
+def _response_payload(response):
+ try:
+ return response.json()
+ except ValueError:
+ return response.text
+
+
+class RunPodAPIError(RuntimeError):
+ def __init__(self, response):
+ self.status_code = response.status_code
+ self.payload = _response_payload(response)
+ if isinstance(self.payload, dict):
+ detail = self.payload.get("detail") or self.payload.get("title") or self.payload.get("error")
+ errors = self.payload.get("errors")
+ if errors:
+ detail = f"{detail}: {json.dumps(errors)}"
+ else:
+ detail = self.payload
+ super().__init__(f"RunPod API returned HTTP {self.status_code}: {detail}")
+
+
+CAPACITY_ERROR_MARKERS = (
+ "no longer any instances available",
+ "no available instances",
+ "no instances available",
+ "insufficient capacity",
+ "no capacity",
+ "out of capacity",
+)
+
+
+def _is_capacity_error(error):
+ if error.status_code != 400:
+ return False
+ payload = error.payload if isinstance(error.payload, str) else json.dumps(error.payload, default=str)
+ payload = payload.lower()
+ return any(marker in payload for marker in CAPACITY_ERROR_MARKERS)
+
+
+class RunPodV2Client:
+ def __init__(self, api_key, session=None):
+ self.session = session if session is not None else requests.Session()
+ self.headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
+
+ def request(self, method, path, retries=3, retry_delay=5, **kwargs):
+ headers = {**self.headers, **kwargs.pop("headers", {})}
+ timeout = kwargs.pop("timeout", REQUEST_TIMEOUT)
+
+ for attempt in range(retries + 1):
+ try:
+ response = self.session.request(
+ method,
+ f"{V2_BASE_URL}{path}",
+ headers=headers,
+ timeout=timeout,
+ **kwargs,
+ )
+ except requests.exceptions.RequestException:
+ if attempt >= retries:
+ raise
+ print(f"⚠️ Request failed, retrying in {retry_delay} seconds ({attempt + 1}/{retries})...")
+ time.sleep(retry_delay)
+ continue
- if response.status_code >= 500 or response.status_code == 400:
- if attempt < max_retries:
- print(f"⚠️ {response.status_code} Error, Retrying in 90 seconds ({attempt + 1}/{max_retries})...")
- time.sleep(90)
+ if response.status_code in RETRYABLE_STATUS_CODES and attempt < retries:
+ print(
+ f"⚠️ {response.status_code} Error, Retrying in {retry_delay} seconds "
+ f"({attempt + 1}/{retries})..."
+ )
+ time.sleep(retry_delay)
continue
- else:
- print(f"❌ {response.status_code} Error, Reached maximum retry attempts ({max_retries}), giving up.")
+ if response.status_code >= 400:
+ raise RunPodAPIError(response)
+ return response
+
+ raise RuntimeError(f"RunPod request failed after {retries} retries")
+
+ def request_json(self, method, path, **kwargs):
+ response = self.request(method, path, **kwargs)
try:
- result = response.json()
+ return response.json()
except ValueError:
- result = {}
+ return {}
+
+
+def run_create_pod(api_key, payload, client=None):
+ client = client if client is not None else RunPodV2Client(api_key)
+ return client.request_json("POST", "/pods", retries=3, retry_delay=90, json=payload) # rp-migrate: ignore
+
+
+def _parse_env(values):
+ env = {}
+ for value in values or []:
+ key, separator, item = value.partition("=")
+ if not separator or not key:
+ raise ValueError(f"Invalid environment variable '{value}', expected KEY=VALUE")
+ env[key] = item
+ return env
+
+
+def _get_gpu_catalog(client, gpu_count, min_cuda_version):
+ params = [
+ ("include", "AVAILABILITY"),
+ ("product", "POD"),
+ ("count", str(gpu_count)),
+ ("cloud", "SECURE"),
+ ]
+ params.append(("minCudaVersion", min_cuda_version)) # rp-migrate: ignore
+ data = client.request_json("GET", "/catalog/gpus", params=params)
+ gpus = data.get("gpus") if isinstance(data, dict) else None
+ if not isinstance(gpus, list):
+ raise RuntimeError("RunPod v2 GPU catalog response did not contain a 'gpus' list")
+ return gpus
+
+
+def _available_data_centers(gpu):
+ return [
+ data_center["id"]
+ for data_center in gpu.get("dataCenters", [])
+ if data_center.get("id")
+ and data_center["id"] not in DATA_CENTER_BAN_LIST
+ and data_center.get("availability", "NONE") != "NONE"
+ ]
+
+
+def _gpu_candidates(gpus):
+ catalog_by_id = {gpu.get("id"): gpu for gpu in gpus if gpu.get("id")}
+ candidates = []
+ for gpu_id in TARGET_GPUS:
+ gpu = catalog_by_id.get(gpu_id)
+ if not gpu:
+ continue
+ data_center_ids = _available_data_centers(gpu)
+ if data_center_ids:
+ candidates.append((gpu_id, data_center_ids))
+ return candidates
+
+
+def _pod_payload(args, gpu_id, data_center_ids, env, min_cuda_version):
+ return {
+ "name": args.name,
+ "image": CU130_IMAGES_NAME,
+ "cloud": "SECURE",
+ "disk": args.container_disk_size,
+ "dataCenterIds": data_center_ids,
+ "env": env,
+ "gpu": {
+ "id": gpu_id,
+ "count": args.gpu_count,
+ "minCudaVersion": min_cuda_version, # rp-migrate: ignore
+ },
+ }
- if "errors" in result:
- print("❌ API Errors:")
- print(json.dumps(result["errors"], indent=2))
+def create_pod(args):
+ if not args.name:
+ raise ValueError("--name is required for pod creation")
+ if args.gpu_count < 1:
+ raise ValueError("--gpu_count must be at least 1")
+
+ env = _parse_env(args.env)
+ min_cuda_version = MIN_CUDA_VERSION
+ client = RunPodV2Client(args.api_key)
+ gpus = _get_gpu_catalog(client, args.gpu_count, min_cuda_version)
+ candidates = _gpu_candidates(gpus)
+ if not candidates:
+ raise RuntimeError("No requested GPU has availability in the selected data centers")
+
+ print(f"🚀 Creating pod: {args.name}...")
+ last_error = None
+ for gpu_id, data_center_ids in candidates:
+ payload = _pod_payload(args, gpu_id, data_center_ids, env, min_cuda_version)
+ print(f" Trying GPU: {gpu_id} in {', '.join(data_center_ids)}")
try:
- response.raise_for_status()
- except requests.exceptions.HTTPError as e:
- print(f"❌ HTTP Error: {e}")
- if result:
- print("Response payload:", json.dumps(result, indent=2))
- else:
- print("Response text:", response.text)
- sys.exit(1)
+ data = run_create_pod(args.api_key, payload, client=client)
+ except RunPodAPIError as error:
+ if not _is_capacity_error(error):
+ raise
+ last_error = error
+ print(f"⚠️ No capacity for {gpu_id}; trying the next available GPU. {error}")
+ continue
- return result
+ pod_id = data.get("id") if isinstance(data, dict) else None
+ if not pod_id:
+ raise RuntimeError("RunPod v2 create response did not contain a pod id")
+ print(f"✅ Pod created successfully! Pod ID: {pod_id}")
+ print(f" Status is: {data.get('status', 'unknown')}")
+ return
+ if last_error:
+ raise RuntimeError(f"No capacity for the requested GPUs. Last API error: {last_error}") from last_error
+ raise RuntimeError("Failed to create pod")
-def create_pod(args):
- if args.env:
- env_dict = {kv.split("=", 1)[0]: kv.split("=", 1)[1] for kv in args.env}
-
- payload = {
- "allowedCudaVersions": [args.cuda_version] if (args.cuda_version and args.cuda_version in CUDA_VERSIONS) else CUDA_VERSIONS,
- "cloudType": "SECURE",
- "containerDiskInGb": args.container_disk_size,
- "dataCenterIds": DATA_CENTER_SELECT_LIST,
- "dataCenterPriority": "availability",
- "env": env_dict,
- "gpuCount": args.gpu_count,
- "gpuTypeIds": TARGET_GPUS,
- "gpuTypePriority": "custom",
- "name": args.name,
- "volumeInGb": 0,
- "imageName": CU130_IMAGES_NAME,
- }
- print(f"🚀 Creating pod: {args.name}...")
- data = run_create_pod(args.api_key, payload)
- if data:
- pod_id = data.get("id")
- location = data.get("machine", {}).get("location", "unknown")
- if pod_id:
- print(f"✅ Pod created successfully! Pod ID: {pod_id}, Location: {location}")
- print(f" Status is: {data.get('desiredStatus')}")
- else:
- print("❌ Failed to create pod (no data returned).")
- sys.exit(1)
-
-
-def get_pod_id(args):
- url = f"https://rest.runpod.io/v1/pods?name={args.name}"
- headers = {"Authorization": "Bearer " + args.api_key}
+def _list_pods(client):
+ data = client.request_json("GET", "/pods") # rp-migrate: ignore
+ pods = data.get("pods") if isinstance(data, dict) else None # rp-migrate: ignore
+ if not isinstance(pods, list):
+ raise RuntimeError("RunPod v2 pod list response did not contain a 'pods' list") # rp-migrate: ignore
+ return pods
+
+
+def _get_pod_by_name(args, client):
+ matches = [pod for pod in _list_pods(client) if pod.get("name") == args.name]
+ return matches[0] if matches else None
+
+
+def _get_pod_by_id(pod_id, client):
try:
- response = requests.get(url, headers=headers)
- response.raise_for_status()
- data = response.json()[0] if response.json() else None
- if data:
- print(f"Pod status: {data.get('desiredStatus', 'unknown')}")
- if data and "id" in data:
- return data["id"]
+ return client.request_json("GET", f"/pods/{pod_id}")
+ except RunPodAPIError as error:
+ if error.status_code == 404:
+ return None
+ raise
- print(f"⚠️ Pod '{args.name}' not found.")
- return None
- except Exception as e:
- print(f"⚠️ Error fetching pods: {e}")
- raise e
+def get_pod_id(args, client=None):
+ client = client if client is not None else RunPodV2Client(args.api_key)
+ pod = _get_pod_by_name(args, client)
+ if pod:
+ print(f"Pod status: {pod.get('status', 'unknown')}")
+ return pod.get("id")
+ print(f"⚠️ Pod '{args.name}' not found.")
+ return None
def wait_for_pod(args):
- for _ in range(60): # Wait up to 10 minutes
- pod_id = get_pod_id(args)
- if pod_id:
- print(f"✅ Pod '{args.name}' is now available with ID: {pod_id}")
- return
+ if not args.name:
+ raise ValueError("--name is required while waiting for a pod")
+ client = RunPodV2Client(args.api_key)
+ for _ in range(60):
+ pod = _get_pod_by_name(args, client)
+ if pod:
+ status = pod.get("status", "unknown")
+ if status in {"ERROR", "EXITED", "TERMINATED"}:
+ raise RuntimeError(f"Pod '{args.name}' entered terminal status {status}")
+ if status == "RUNNING":
+ print(f"✅ Pod '{args.name}' is now available with ID: {pod.get('id')} (status: {status})")
+ return
+ print(f"⏳ Pod '{args.name}' is {status}; waiting until it is RUNNING...")
else:
print(f"⏳ Waiting for pod '{args.name}' to be created...")
- time.sleep(10)
+ time.sleep(10)
print(f"❌ Timeout: Pod '{args.name}' was not created within the expected time.")
- sys.exit(1)
+ raise RuntimeError(f"Pod '{args.name}' was not created within the expected time")
def terminate_pod(args):
- pod_id = args.pod_id or get_pod_id(args)
+ client = RunPodV2Client(args.api_key)
+ pod_id = args.pod_id or get_pod_id(args, client)
if not pod_id:
- get_pod_id(args) # Just to check if pod exists and print status
- sys.exit(1)
-
- url = f"https://rest.runpod.io/v1/pods/{pod_id}"
- headers = {"Authorization": f"Bearer {args.api_key}"}
-
- max_tries = 30
+ raise RuntimeError(f"Pod '{args.name or 'unknown'}' not found")
- for attempt in range(max_tries + 1):
- response = requests.delete(url, headers=headers)
- if response.status_code >= 500 or response.status_code == 400:
- if attempt < max_tries:
- print(f"⚠️ {response.status_code} Error, Retrying in 5 seconds ({attempt + 1}/{max_tries})...")
- time.sleep(5)
- continue
- else:
- print(f"❌ {response.status_code} Error, Reached maximum retry attempts ({max_tries}), giving up.")
- else:
- break
-
- response.raise_for_status()
-
- for i in range(max_tries): # Wait up to 5 minutes for termination
- pod_id = get_pod_id(args)
- if pod_id:
- print(f"⚠️ Pod {args.name}: {pod_id} termination initiated, but pod still exists")
- if i >= max_tries - 1:
- raise Exception(
- f"❌ Pod {args.name}: {pod_id} termination may not have completed yet. Please check the status."
- )
- else:
- print(f"✅ Pod {args.name} termination command sent.")
- break
- time.sleep(10) # Wait a bit for termination to process
+ try:
+ client.request("DELETE", f"/pods/{pod_id}", retries=30, retry_delay=5)
+ except RunPodAPIError as error:
+ if error.status_code != 404:
+ raise
+ print(f"✅ Pod {args.name or pod_id} was already terminated.")
+ return
+
+ for attempt in range(30):
+ pod = _get_pod_by_id(pod_id, client)
+ if pod is None:
+ print(f"✅ Pod {args.name or pod_id} termination command sent.")
+ return
+ print(f"⚠️ Pod {args.name or pod_id}: {pod_id} termination initiated, but pod still exists")
+ if attempt < 29:
+ time.sleep(10)
+ raise RuntimeError(f"Pod {args.name or pod_id}: termination may not have completed yet")
def main():
@@ -203,7 +312,6 @@ def main():
parser.add_argument("--gpu_count", type=int, default=1)
parser.add_argument("--container_disk_size", type=int, default=50)
parser.add_argument("--part", type=int, default=0)
- parser.add_argument("--cuda_version", help="CUDA version for the pod")
parser.add_argument("--env", nargs="*", help="Environment variables in KEY=VALUE format")
args = parser.parse_args()
diff --git a/.azure-pipelines/unit-test-cuda.yml b/.azure-pipelines/unit-test-cuda.yml
index aa4d656ca..d664f6fe0 100644
--- a/.azure-pipelines/unit-test-cuda.yml
+++ b/.azure-pipelines/unit-test-cuda.yml
@@ -71,15 +71,12 @@ stages:
inputs:
targetType: "inline"
script: |
- CUDA_VERSION="13.0"
-
python .azure-pipelines/scripts/cuda_unit_test/runpod_manager.py \
--action create \
--api_key $(RUNPOD_API_KEY) \
--name "ci-$(Build.BuildId)-${{ pair.value.PART }}" \
--container_disk_size "100" \
--part ${{ pair.value.PART }} \
- --cuda_version "${CUDA_VERSION}" \
--env AZP_URL=$(System.CollectionUri) AZP_TOKEN=$(AZP_DEVOPS_PAT) AZP_POOL=$(POOL_NAME) AZP_AGENT_NAME="$(AGENT_NAME)-part${{ pair.value.PART }}"
env:
PYTHONUNBUFFERED: '1'
diff --git a/.claude/skills/review-pr/SKILL.md b/.claude/skills/review-pr/SKILL.md
index 215163c37..48868c9e6 100644
--- a/.claude/skills/review-pr/SKILL.md
+++ b/.claude/skills/review-pr/SKILL.md
@@ -10,13 +10,19 @@ description: "Review or prepare a pull request for the AutoRound repository —
Follow these steps in order. Stop and request changes at any gate that fails.
1. **Scope check** — read the PR description and diff summary. Confirm the PR does one thing and unrelated changes are absent. If scope is unclear, request changes before proceeding.
-2. **Code quality gate** — run through the Code Quality checklist below. Any failure → request changes.
-3. **Quantization review** — if the PR touches `auto_round/` quantization logic, run the Quantization-Specific checklist. Any numerical stability concern → request changes.
-4. **Registration audit** — if the PR adds a new feature type (data type, export format, VLM, backend, dataset, scheme), verify every registration point in the table below is updated. Missing registration → request changes.
-5. **Test verification** — confirm new functionality has tests in the correct backend directory with minimal iterations. Missing or misplaced tests → request changes.
-6. **Documentation & translation** — check README/docs updates and run the Chinese Translation Verification procedure below. Missing `_CN.md` updates for modified markdown → request changes.
-7. **Contributing requirements** — verify DCO sign-off, clean commits, and clear PR description.
-8. **Decision** — if all gates pass, approve. Otherwise, summarize all findings in a single review comment with specific file:line references.
+2. **Pre-commit validation** — install `pre-commit` if needed and run all configured checks:
+ ```bash
+ pip install pre-commit
+ pre-commit run --all-files
+ ```
+ Any failure → request changes.
+3. **Code quality gate** — run through the Code Quality checklist below. Any failure → request changes.
+4. **Quantization review** — if the PR touches `auto_round/` quantization logic, run the Quantization-Specific checklist. Any numerical stability concern → request changes.
+5. **Registration audit** — if the PR adds a new feature type (data type, export format, VLM, backend, dataset, scheme), verify every registration point in the table below is updated. Missing registration → request changes.
+6. **Test verification** — confirm new functionality has tests in the correct backend directory with minimal iterations. Missing or misplaced tests → request changes.
+7. **Documentation & translation** — check README/docs updates and run the Chinese Translation Verification procedure below. Missing `_CN.md` updates for modified markdown → request changes.
+8. **Contributing requirements** — verify DCO sign-off, clean commits, and clear PR description.
+9. **Decision** — if all gates pass, approve. Otherwise, summarize all findings in a single review comment with specific file:line references.
## Review Checklist
diff --git a/AGENTS.md b/AGENTS.md
index 78f74ad33..e560b2a68 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -47,14 +47,33 @@ pytest test/e2e/test_cpu/
Test fixtures create tiny models (OPT-125M, Qwen-0.6B) at session scope — first run downloads them.
-## Code Style
-
-- **Line length: 120** (non-default) — enforced by black, isort, ruff, pylint
-- **Formatter: black** (profile used by isort)
-- **Import sorting: isort** with `profile=black`, first-party: `auto_round`, `auto_round_extension`
-- **Linter: ruff** — rules `E4, E7, E9, F, NPY, FURB`; E501/E402/F401/F403 are intentionally ignored
-- **License header**: Apache 2.0 auto-inserted into `.py/.yaml/.yml/.sh` under `auto_round/` and `auto_round_extension/`
-- Pre-commit config: `.pre-commit-config.yaml`
+## Code Quality & Pre-commit
+
+All syntax, formatting, licensing, spelling, and linting checks are enforced via `.pre-commit-config.yaml`.
+
+### Execution Rules for Agents
+
+1. **Always run pre-commit after editing files**:
+ - For focused changes (preferred):
+ ```bash
+ pre-commit run --files <changed_file1> <changed_file2>
+ ```
+ - For a specific hook/tool (e.g., `ruff`, `black`, `codespell`):
+ ```bash
+ pre-commit run <hook_id> --files <changed_file>
+ ```
+ - For repository-wide checks (recommended for extensive changes or initial runs; fast and lightweight):
+ ```bash
+ pre-commit run --all-files
+ ```
+2. **Rerun until clean**: Tools like `ruff` and `codespell` automatically fix issues but will exit with non-zero on first modification (`--exit-non-zero-on-fix`). Keep changes and rerun the command until all checks pass.
+3. **Manual fixes**: Only make manual changes if a check fails and cannot be auto-fixed (e.g., `bandit` security findings, `check-json`, or complex syntax errors).
+
+### Automated Checks Summary
+
+- **Auto-fixing hooks**: `black` (line length 120), `isort` (imports), `ruff` (lint fixes), `insert-license` (Apache 2.0 header), `codespell` (typos), `mixed-line-ending` (LF).
+- **Check-only hooks**: `bandit` (security issues under `auto_round/`), `typos`, `check-yaml`/`check-json`, `markdown-link-check`.
+- *Note*: `auto_round/export/export_to_gguf/conversion/` is intentionally excluded from most hooks.
## Commit & PR Conventions