Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions SOURCE-SHA256.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@
"gpuqueue/control.py": "1412129e7f0f7c4f67db0c4c11f3e66f24cc1353f7bf67ad13b2ef86ae29de28",
"gpuqueue/core.py": "a726498140ffc19076a461b9254ef3cb7ce7085119bd11997650f2068fef4c24",
"gpuqueue/host_monitor.py": "ec685be9bf9e498eefe7f9b8719b06a581853df01dd006ade239d70ef6196e4b",
"gpuqueue/platform.py": "1c4aad5ea1c2f41937ebaeafec03a5cc99ffee7d2dda706446d9919e49277f9d",
"gpuqueue/runner.py": "300c18ee4360bdf320f1a02c9a1eae21cca33d39347f4157b43e705f5177c304",
"gpuqueue/serverbox.py": "204470fb517ccd27609f5b2d1d68fa30d1a53f541a18d8e4412761fa8023817c",
"gpuqueue/platform.py": "960be0be5133a4db752da705da0c5880bb7050f4772a5acc66a169a2b99d894b",
"gpuqueue/runner.py": "7f20c357c0df5e3c07ececa3d0a95648b5ae3c74bfd1c4ffba85e03396bf4756",
"gpuqueue/serverbox.py": "00de2db3e01a89525f69dd0c55d75d92d340c0aa552817cd255d58062f8c9c55",
"gpuqueue/service.py": "df60d5d835a3baef689dba4a80362088c07eea1e711ecc7244fda4ed504d9972",
"gpuqueue/stop_control.py": "10d2241a2882dbb97605f4fcb364c6f6fbe01451b8d90137d3aed1ff859433f7",
"gpuqueue/web.py": "e399f5a728767bd1ffe7845f50a54f73a98c7771611a7f1b40addb5b21064ee1",
Expand Down Expand Up @@ -63,7 +63,7 @@
"tests/local_server.mjs": "f7b943a06fc8881d9e083a05ff556948d8f8273b6fff59bb681e6ad5633520fa",
"tests/modes.test.cjs": "f55a0afd571abe617a9c0cf1dc3f2591085d58dcad5435fd45382e6705548038",
"tests/monitor.test.js": "54fa84e136fe8d9303ec0bfa873d53a402a1cdd34adfd3eb475f32678efc5e0d",
"tests/test_gpuqueue.py": "614df82d4652e8d529d5c030df852aabc766f9b03427bf2acf8d286a4e0cc316",
"tests/test_gpuqueue.py": "c657e41630e8f25e4b4c65b84eb9621f9cfc60389d7ed1290218c7437a669972",
"tests/test_host_monitor.py": "951bc42312a4cf24437a114cdf2881e6d6e119992d8a32d0fc4a4f73aa13c494",
"tests/test_launcher.py": "c336ce79267510501294ee1f73600b5b57ab8143469d75a8cf5d827e650e941d",
"tests/test_local.py": "ebdb961978ede03745d8bb2eb7e8bc2624e4f88628574af590a0a2d8287d4bc4",
Expand Down
196 changes: 123 additions & 73 deletions gpuqueue/platform.py

Large diffs are not rendered by default.

132 changes: 125 additions & 7 deletions gpuqueue/runner.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,125 @@
"""Foreground GPU pipeline. Reads immutable input; never applies for resources."""
import datetime as dt
import csv
import hashlib
import json
import math
import os
from pathlib import Path
from queue import Empty, Queue
import selectors
import socket
import subprocess
import sys
import tempfile
from threading import Thread
import time
import selectors

TELEMETRY_INTERVAL = 15
GPU_FIELDS = 'index,uuid,name,memory.total,memory.used,utilization.gpu,temperature.gpu'
UNAVAILABLE_METRICS = {'N/A', '[N/A]', 'Not Supported', '[Not Supported]'}


def validate_telemetry(payload, current):
"""Check and allowlist the fields shared by runner and probe samples."""
stamp = payload['at']
if type(stamp) not in (int, float) or not math.isfinite(stamp) or not 0 < stamp <= current+5:
raise ValueError('Invalid GPU sample time')
host = payload.get('host', '')
if not isinstance(host, str):
raise ValueError('Invalid GPU host')
if not isinstance(payload['gpus'], list) or not isinstance(payload['apps'], list):
raise ValueError('Invalid GPU telemetry')

gpus, indexes, devices = [], set(), set()
for gpu in payload['gpus']:
index, device, name = (gpu[key] for key in ('index', 'uuid', 'name'))
total, used, utilization = (gpu[key] for key in ('total_mb', 'used_mb', 'utilization'))
temperature = gpu.get('temperature_c')
metrics = (total, used, utilization) if temperature is None else (total, used, utilization, temperature)
if (type(index) is not int or index < 0 or index in indexes
or not isinstance(device, str) or not device.strip() or device in devices
or not isinstance(name, str) or not name.strip()
or any(type(n) not in (int, float) or not math.isfinite(n) or n < 0 for n in metrics)
or total <= 0 or used > total or utilization > 100):
raise ValueError('Invalid GPU metrics')
indexes.add(index)
devices.add(device)
gpus.append(dict(index=index, uuid=device, name=name, total_mb=total,
used_mb=used, utilization=utilization, temperature_c=temperature))
if not gpus:
raise ValueError('Missing GPU metrics')

apps = payload['apps']
for row in apps:
if (not isinstance(row, list) or len(row) != 2
or not isinstance(row[0], str) or not row[0].strip()
or not isinstance(row[1], str) or not row[1].isdecimal()):
raise ValueError('Invalid GPU compute process')
return dict(gpus=gpus, apps=apps, at=stamp, host=host)


def parse_smi_telemetry(payload, current):
gpus = []
for row in csv.reader(payload['gpus'].splitlines(), skipinitialspace=True):
if len(row) not in (6, 7):
raise ValueError('Invalid GPU metrics')
temperature = row[6].strip() if len(row) == 7 else 'N/A'
gpus.append(dict(index=int(row[0]), uuid=row[1].strip(), name=row[2].strip(),
total_mb=float(row[3]), used_mb=float(row[4]), utilization=float(row[5]),
temperature_c=None if temperature in UNAVAILABLE_METRICS else float(temperature)))
apps = [[field.strip() for field in row]
for row in csv.reader(payload['apps'].splitlines(), skipinitialspace=True)]
return validate_telemetry(dict(gpus=gpus, apps=apps, at=payload['at'],
host=payload.get('host', '')), current)


def query_smi(fields):
result = subprocess.run(['nvidia-smi', fields, '--format=csv,noheader,nounits'],
capture_output=True, text=True, timeout=5)
result.check_returncode()
return result.stdout.strip()


class TelemetrySampler:
"""Run at most one sample off the heartbeat and log-draining thread."""
def __init__(self):
self.next_at = time.monotonic()
self.results = Queue(maxsize=1)
self.pending = False

def sample(self):
try:
gpus = query_smi('--query-gpu='+GPU_FIELDS)
stamp = time.time()
apps = query_smi('--query-compute-apps=gpu_uuid,pid')
sample = parse_smi_telemetry(dict(gpus=gpus, apps=apps, at=stamp,
host=socket.gethostname()), time.time())
except Exception:
sample = None
self.results.put_nowait(sample)

def collect(self, status):
if self.pending:
try:
sample = self.results.get_nowait()
except Empty:
return
self.pending = False
if sample is not None and sample['at'] > status.get('telemetry', {}).get('at', 0):
status['telemetry'] = sample

def tick(self, status):
self.collect(status)
current = time.monotonic()
if current >= self.next_at:
self.next_at = current + TELEMETRY_INTERVAL
if not self.pending:
try:
Thread(target=self.sample, daemon=True).start()
self.pending = True
except Exception:
pass


def write(path, value):
fd, temporary = tempfile.mkstemp(dir=path.parent, prefix='.state-')
Expand Down Expand Up @@ -66,6 +177,8 @@ def execute(folder):
if len(device_ids) != doc['resources']['gpus'] or not set(device_ids).issubset(set(gpu.stdout.split())):
raise RuntimeError('Assigned GPU identity is unavailable')
status['gpu_verified'] = True
sampler = TelemetrySampler()
sampler.tick(status)
for index, step in enumerate(doc['steps']):
# Verify the frozen code again at step boundaries.
for relative, digest in doc['files'].items():
Expand All @@ -92,7 +205,7 @@ def execute(folder):
selector.register(process.stdout, selectors.EVENT_READ)
while selector.get_map():
# Output must not trigger a status fsync or delay the next heartbeat.
timeout = max(0, 10 - (time.monotonic() - heartbeat_at))
timeout = max(0, min(heartbeat_at+10, sampler.next_at) - time.monotonic())
for key, _ in selector.select(timeout=timeout):
chunk = os.read(key.fileobj.fileno(), 65536)
if not chunk:
Expand All @@ -102,6 +215,7 @@ def execute(folder):
os.replace(log, log.with_suffix('.previous.log'))
with log.open('ab') as stream:
stream.write(chunk)
sampler.tick(status)
heartbeat_now = time.monotonic()
if heartbeat_now - heartbeat_at >= 10:
status['updated_at'] = time.time()
Expand All @@ -111,14 +225,18 @@ def execute(folder):
process.stdout.close()
# EOF only closes the log stream; the child may still be computing.
while True:
timeout = max(0, 10 - (time.monotonic() - heartbeat_at))
timeout = max(0, min(heartbeat_at+10, sampler.next_at) - time.monotonic())
try:
code = process.wait(timeout=timeout)
break
except subprocess.TimeoutExpired:
status['updated_at'] = time.time()
write(state_file, status)
heartbeat_at = time.monotonic()
sampler.tick(status)
heartbeat_now = time.monotonic()
if heartbeat_now - heartbeat_at >= 10:
status['updated_at'] = time.time()
write(state_file, status)
heartbeat_at = heartbeat_now
sampler.collect(status)
record.update(exit_code=code, finished_at=time.time())
if code != 0:
record['state'] = 'failed'
Expand Down
11 changes: 9 additions & 2 deletions gpuqueue/serverbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
from .resources import published_resources


FRESH_TTL_S = 180


def metric(value):
if value is None:
return None
Expand All @@ -29,9 +32,13 @@ def publish(resources, home):
memory_used_mib=metric(gpu['used_mb']),
memory_total_mib=metric(gpu['total_mb']),
temperature_c=metric(gpu.get('temperature_c'))))
monitor_state = (resource.get('monitor') or {}).get('state')
if not monitor_state and resource.get('probe'):
monitor_state = 'sampling'
records.append(dict(request=request, status=resource['status'],
collected_at=stamp, host=telemetry.get('host', ''), gpus=gpus,
monitor={key: resource['monitor'][key] for key in ['state'] if key in resource.get('monitor', {})},
collected_at=stamp, fresh_ttl_s=FRESH_TTL_S,
host=telemetry.get('host', ''), gpus=gpus,
monitor={'state': monitor_state} if monitor_state else {},
release_pending=resource.get('release', {}).get('state') == 'pending_interface'))
path = Path(home)/'.local/state/serverbox-gpu/registry.json'
atomic_json(path, dict(schema=1, source='gpuq', updated_at=time.time(), resources=records))
4 changes: 2 additions & 2 deletions tests/test_gpuqueue.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,13 +185,13 @@ def test_runner_real_child_burst_preserves_all_output_with_few_status_writes(sel
def test_runner_silent_child_keeps_ten_second_heartbeats(self):
result, _, writes, timeouts, _ = self.run_output_events([(30.5, b'')])
self.assertEqual(result, 0)
self.assertEqual(timeouts, [10, 10, 10, 10])
self.assertEqual(timeouts, [10, 5, 5, 10, 10])
self.assertEqual([at for at, _ in writes[3:-2]], [10, 20, 30])

def test_runner_output_before_silence_does_not_postpone_heartbeat(self):
result, _, writes, timeouts, _ = self.run_output_events([(9.75, b'progress'), (20.5, b'')])
self.assertEqual(result, 0)
self.assertEqual(timeouts, [10, 0.25, 10, 10])
self.assertEqual(timeouts, [10, 0.25, 5, 5, 10])
self.assertEqual([at for at, _ in writes[3:-2]], [10, 20])

def test_runner_early_eof_keeps_heartbeat_until_child_exits(self):
Expand Down
3 changes: 1 addition & 2 deletions tests/test_probe_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ def write_runner(self, **changes):
updated_at=time.time(), **changes))

def recover(self):
self.adapter.recover_active_probe(self.resource)
self.adapter.refresh_probe(self.resource)

def test_fresh_runner_recovers_only_readonly_probe_and_needs_real_sample(self):
Expand Down Expand Up @@ -72,7 +71,7 @@ def test_historical_running_receipt_without_fresh_runner_cannot_retry(self):
self.adapter.submit_job.assert_not_called()

def test_pending_probe_is_kept_and_late_receipt_is_consumed_without_duplicates(self):
self.resource.update(status='online', probe=dict(job=JOB, at=time.time()-101))
self.resource.update(status='online', probe=dict(job=JOB, at=time.time()-181))
specification = self.adapter.job_folder(REQUEST)/(JOB+'.json')
atomic_json(specification, dict(argv=['read-only-probe']))
self.adapter.refresh_probe(self.resource)
Expand Down
6 changes: 3 additions & 3 deletions tests/test_request_diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def test_pending_request_keeps_resource_and_execution_admission_checks(self):
REQUEST: dict(id=REQUEST, status='pending', recorded_phase='submitted'),
'available': resource,
}
for change in [dict(at=time.time()-100),
for change in [dict(at=time.time()-181),
dict(gpus=[dict(uuid='GPU-1', total_mb=81920, used_mb=81920)]),
dict(apps=[['GPU-1', '999']])]:
with self.subTest(change=change):
Expand All @@ -177,7 +177,7 @@ def test_pending_request_keeps_resource_and_execution_admission_checks(self):
def test_late_probe_reuses_old_gpu_once_and_preserves_pending_replacement(self):
task = self.task()
old = self.enable_replacement()
old['probe'] = dict(job='late-probe', at=time.time()-101)
old['probe'] = dict(job='late-probe', at=time.time()-181)
self.adapter.lark = Mock(side_effect=[{'questions': []}, {'record_id': 'new-receipt'}])
self.service.cycle()
task = self.store.get(task['id'])
Expand Down Expand Up @@ -451,7 +451,7 @@ def test_existing_healthy_gpu_is_reused_before_requesting_replacement(self):
self.adapter.lark.assert_not_called()

def test_actual_probe_timeout_records_evidence_without_claiming_release(self):
resource = dict(id=REQUEST, status='ready', probe=dict(job='unclaimed', at=time.time()-101))
resource = dict(id=REQUEST, status='ready', probe=dict(job='unclaimed', at=time.time()-181))
self.adapter.refresh_probe(resource)
self.assertTrue(self.adapter.probe_timed_out(resource))
self.assertEqual(resource['status'], 'unknown')
Expand Down
10 changes: 5 additions & 5 deletions tests/test_resource_monitoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,15 @@ def online(self, age=0):
class MonitoringTests(MonitoringFixture):
def test_periods_use_actual_sample_time_in_both_ready_and_online(self):
for status in ['ready', 'online']:
for active, age, count in [(False, 59, 0), (False, 60, 1), (True, 9, 0), (True, 10, 1)]:
for active, age, count in [(False, 59, 0), (False, 60, 1), (True, 1, 0), (True, 2, 1)]:
with self.subTest(status=status, active=active, age=age):
resource = dict(self.online(age), status=status)
self.adapter.resources = {REQUEST: resource}
self.adapter.submit_job.reset_mock()
self.adapter.refresh(active=active)
self.assertEqual(self.adapter.submit_job.call_count, count)

def test_idle_to_active_rechecks_ten_second_period_in_same_tick(self):
def test_idle_to_active_rechecks_two_second_period_in_same_tick(self):
resource = self.online(20)
self.adapter.resources = {REQUEST: resource}
self.adapter.refresh(active=False)
Expand All @@ -78,7 +78,7 @@ def test_initial_and_explicit_samples_bypass_idle_period(self):
self.adapter.submit_job.assert_called_once()

def test_inflight_and_late_receipt_keep_exact_job_and_sample_time(self):
resource = dict(self.online(60), probe=dict(job=JOB, at=NOW-101))
resource = dict(self.online(60), probe=dict(job=JOB, at=NOW-181))
self.adapter.resources = {REQUEST: resource}
spec = self.adapter.job_folder(REQUEST)/(JOB+'.json')
atomic_json(spec, dict(argv=['read-only-probe']))
Expand All @@ -101,9 +101,9 @@ def test_inflight_and_late_receipt_keep_exact_job_and_sample_time(self):
self.adapter.submit_job.assert_called_once()
self.assertTrue(spec.exists())

def test_selection_keeps_ninety_second_actual_telemetry_boundary(self):
def test_selection_uses_180_second_actual_telemetry_boundary(self):
task = dict(internal={}, doc=dict(resources=dict(type='H卡离线', gpus=1, memory_gb=1)))
for age, ready in [(89, True), (90, True), (90.001, False)]:
for age, ready in [(179, True), (180, True), (180.001, False)]:
with self.subTest(age=age):
self.adapter.resources = {REQUEST: self.online(age)}
selection, _ = self.adapter.select(task, [])
Expand Down
Loading
Loading