Files
nvdriver/tools/hbm_gate.py
morebrackets ca610d4d71 Address all 5 Greptile review findings on #207 (tools/hbm_gate.py)
- Per-device NDIV map (4777555006): on GV100, use v100_hbm_ndiv_map with
  normalized PCI BDF overrides (preserving all other GPUs' entries) instead
  of mutating the global v100_hbm_ndiv parameter; fail closed if target BDF
  cannot be resolved.
- Hardware restore verification (4777555018): add verify_restored_clock()
  and require live hardware memory-clock readback to confirm baseline clock
  restoration in restore_sysfs_ndiv() / restore_sysfs_ndiv_map().
- Isolated CUDA sweep worker with timeout (4777555035): add
  run_cuda_sweep_subprocess() + --_cuda-sweep-worker + --sweep-timeout-s so
  hung CUDA copies/synchronizes are reaped via process group kill and the
  parent always reaches baseline clock restoration.
- Live telemetry polling during external workloads (4777555042): poll
  telemetry periodically in run_workload_command() and wire it into both
  --workload-only and supplemental --workload paths, reaping the workload
  process group immediately (rc=125) on thermal/ECC/clock violations.
- Single-sweep GEMM drift guard (4777555049): enforce --sweeps >= 2 for
  built-in GEMM sweeps in validate_cli_args(), support baseline reference
  digests in evaluate_gate(), and fail closed on unreferenced single-sweep
  GEMM digests.
- Expanded --self-check to 43 checks (pass under python3 and python3 -O).
2026-12-02 17:02:48 -08:00

2712 lines
106 KiB
Python
Executable File

#!/usr/bin/env python3
"""HBM2 / HBM2e clock & VRAM heat-soak stability verifier (`hbm-gate`, #170 / #174).
Implements the hot-correctness qualification methodology for GP100 (Tesla P100 /
CMP 100-100), GV100 (Tesla V100 / CMP 100-210), and GA100 (A100 / CMP 170HX):
1. Captures baseline sysfs NDIV, volatile ECC SEC/DED counters, GPU/HBM
temperatures, and live hardware memory clock via `nvidia-smi`.
2. Runs a mandatory negative-control canary (injects a 1-bit flip in the
verification comparator and requires detection before trusting any pass).
3. Verifies that any sysfs NDIV write actually changed the measured hardware
memory clock (failing closed with `FAIL_CLOCK_UNAPPLIED` for load-time-only
or rejected parameters).
4. Enforces thermal ceilings before GPU work starts, between every sweep, and
across the descending NDIV ladder (stopping immediately on `FAIL_THERMAL`).
5. Executes deterministic full-buffer multi-pattern VRAM write/readback sweeps
(`0x00`, `0xFF`, `0xAA55AA55`, `0x55AA55AA`, address-XOR) across the entire
allocated `--chunk-mb` region, plus separate FP16 and FP32 GEMM digest checks
(via PyTorch) and optional supplemental `--workload "<cmd>"`, or explicit
`--workload-only --workload "<cmd>"` mode when PyTorch is unavailable.
6. Polls ECC SEC/DED counters, memory clock, and temperatures before, during,
and after sweeps; any missing required telemetry, HBM temperature sensor
dropout (on cards that initially report HBM temperature), non-monotonic
volatile ECC counter, byte mismatch, digest drift, ECC increment, mid-soak
clock drop, or over-temperature fails closed and restores the baseline NDIV
under a per-parameter interprocess lock. On GPUs whose telemetry never
exposes a dedicated HBM memory temperature sensor (`peak_mem_temp_c: null`),
thermal gating enforces the GPU temperature ceiling only (distinguished from
a previously reporting HBM sensor that stops reporting mid-soak, which fails
closed with `FAIL_TELEMETRY_UNAVAILABLE`).
Run `--self-check` for the offline unit test suite (touches no GPU or sysfs).
"""
from __future__ import annotations
import argparse
import contextlib
import fcntl
import hashlib
import json
import math
import os
import re
import shutil
import signal
import struct
import subprocess
import sys
import tempfile
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Callable, Iterator, List, Optional, Sequence, Tuple, Union
SYSFS_PARAM_BY_ARCH = {
"gp100": Path("/sys/module/nvidia_rs/parameters/p100_hbm_ndiv"),
"gv100": Path("/sys/module/nvidia_rs/parameters/v100_hbm_ndiv"),
"ga100": Path("/sys/module/nvidia_rs/parameters/ga100_hbm_ndiv"),
}
SYSFS_MAP_PARAM_BY_ARCH = {
"gv100": Path("/sys/module/nvidia_rs/parameters/v100_hbm_ndiv_map"),
}
DEFAULT_LADDERS = {
"gp100": [66, 62, 58, 55, 53],
"gv100": [82, 78, 74, 70, 67, 65],
"ga100": [80, 76, 72, 70, 67, 64],
}
STEP_MHZ_BY_ARCH = {
"gp100": 13.5,
"gv100": 13.5,
"ga100": 27.0,
}
PATTERN_NAMES = ("zero", "ones", "aa55", "55aa", "addr_xor")
DEFAULT_VERIFY_CHUNK_BYTES = 4 * 1024 * 1024 # 4 MiB chunks across full allocation
DEFAULT_LOCK_DIR = Path("/tmp")
DEFAULT_WORKLOAD_TIMEOUT_S = 600.0
DEFAULT_SWEEP_TIMEOUT_S = 300.0
DEFAULT_TELEMETRY_POLL_INTERVAL_S = 1.0
def clock_tolerance_mhz(arch: str) -> float:
"""Returns a per-architecture clock verification tolerance strictly below half an NDIV step.
Accepts 1 MHz `nvidia-smi` rounding on the requested rung while rejecting adjacent rungs
(e.g. 5.4 MHz for 13.5 MHz GP100/GV100 steps, 10.8 MHz for 27.0 MHz GA100 steps).
"""
return round(STEP_MHZ_BY_ARCH.get(arch, 13.5) * 0.4, 2)
@dataclass
class EccSample:
sec_total: Optional[int] = None
ded_total: Optional[int] = None
gpu_temp_c: Optional[int] = None
mem_temp_c: Optional[int] = None
mem_clock_mhz: Optional[float] = None
available: bool = False
error: str = ""
def __post_init__(self) -> None:
if (
not self.available
and not self.error
and self.sec_total is not None
and self.ded_total is not None
and self.gpu_temp_c is not None
):
self.available = True
@dataclass
class SweepOutcome:
ndiv: Optional[int]
mhz: Optional[float]
verdict: str # PASS | FAIL_NEGATIVE_CONTROL | FAIL_TELEMETRY_UNAVAILABLE | FAIL_CLOCK_UNAPPLIED | FAIL_BYTE_COMPARE | FAIL_ECC_DELTA | FAIL_DIGEST | FAIL_THERMAL | FAIL_WORKLOAD
sweeps_completed: int
mismatched_bytes: int = 0
sec_delta: int = 0
ded_delta: int = 0
peak_gpu_temp_c: Optional[int] = None
peak_mem_temp_c: Optional[int] = None
measured_mem_clock_mhz: Optional[float] = None
gemm_digest: str = ""
fp16_digest: str = ""
fp32_digest: str = ""
thermal_exceeded: bool = False
workload_gpu_verified: Optional[bool] = None
checks_run: List[str] = field(default_factory=list)
notes: List[str] = field(default_factory=list)
def _check(cond: bool, msg: str) -> None:
if not cond:
raise AssertionError(msg)
def generate_pattern_bytes(pattern: str, num_words: int, seed_offset: int = 0) -> bytes:
"""Generates a deterministic 32-bit-word VRAM test buffer."""
if num_words < 0:
raise ValueError("num_words must be non-negative")
if pattern == "zero":
return b"\x00\x00\x00\x00" * num_words
if pattern == "ones":
return b"\xff\xff\xff\xff" * num_words
if pattern == "aa55":
return struct.pack("<I", 0xAA55AA55) * num_words
if pattern == "55aa":
return struct.pack("<I", 0x55AA55AA) * num_words
if pattern == "addr_xor":
words = [
(((seed_offset + i) * 0x9E3779B1) ^ (i << 3) ^ 0xA5A55A5A) & 0xFFFFFFFF
for i in range(num_words)
]
return struct.pack(f"<{num_words}I", *words)
raise ValueError(f"unknown pattern: {pattern}")
def compare_buffers(expected: bytes, observed: bytes) -> Tuple[int, Optional[int]]:
"""Returns `(mismatched_byte_count, first_mismatch_offset)`."""
if len(expected) != len(observed):
diff = abs(len(expected) - len(observed))
n = min(len(expected), len(observed))
first = n
for i in range(n):
if expected[i] != observed[i]:
first = i
diff += 1
return diff, first
if expected == observed:
return 0, None
mismatches = 0
first = None
for i, (a, b) in enumerate(zip(expected, observed)):
if a != b:
if first is None:
first = i
mismatches += 1
return mismatches, first
def run_negative_control(sample_words: int = 256) -> bool:
"""Proves the byte comparator detects a single-bit flip in an address-XOR buffer."""
expected = generate_pattern_bytes("addr_xor", sample_words, seed_offset=17)
corrupted = bytearray(expected)
mid = len(corrupted) // 2
corrupted[mid] ^= 0x01
mismatches, first = compare_buffers(expected, bytes(corrupted))
return mismatches == 1 and first == mid
def iter_chunk_spans(total_bytes: int, chunk_bytes: int = DEFAULT_VERIFY_CHUNK_BYTES) -> List[Tuple[int, int]]:
"""Splits `total_bytes` (aligned to 4-byte words) into `(byte_offset, byte_len)` spans."""
if total_bytes <= 0:
raise ValueError("total_bytes must be positive")
if chunk_bytes <= 0 or (chunk_bytes % 4) != 0:
raise ValueError("chunk_bytes must be a positive multiple of 4")
aligned = total_bytes - (total_bytes % 4)
if aligned == 0:
raise ValueError("total_bytes must be at least 4 bytes")
spans: List[Tuple[int, int]] = []
off = 0
while off < aligned:
size = min(chunk_bytes, aligned - off)
spans.append((off, size))
off += size
return spans
def verify_full_buffer_chunks(
pattern: str,
total_bytes: int,
sweep_idx: int,
write_chunk: Callable[[int, bytes], None],
read_chunk: Callable[[int, int], bytes],
*,
chunk_bytes: int = DEFAULT_VERIFY_CHUNK_BYTES,
sync_fn: Optional[Callable[[], None]] = None,
) -> int:
"""Writes every chunk across the entire `total_bytes` allocation, syncs, then verifies every chunk."""
spans = iter_chunk_spans(total_bytes, chunk_bytes=chunk_bytes)
for byte_off, byte_len in spans:
word_off = byte_off // 4
chunk_words = byte_len // 4
seed = sweep_idx * 1_000_003 + word_off
write_chunk(byte_off, generate_pattern_bytes(pattern, chunk_words, seed_offset=seed))
if sync_fn is not None:
sync_fn()
mismatches = 0
for byte_off, byte_len in spans:
word_off = byte_off // 4
chunk_words = byte_len // 4
seed = sweep_idx * 1_000_003 + word_off
expected = generate_pattern_bytes(pattern, chunk_words, seed_offset=seed)
observed = read_chunk(byte_off, byte_len)
mm, _ = compare_buffers(expected, observed)
mismatches += mm
if mismatches > 0:
return mismatches
return mismatches
def exceeds_thermal_ceiling(sample: EccSample, max_temp_c: int) -> bool:
"""Returns True if any available temperature reading exceeds `max_temp_c`."""
if sample.gpu_temp_c is not None and sample.gpu_temp_c > max_temp_c:
return True
if sample.mem_temp_c is not None and sample.mem_temp_c > max_temp_c:
return True
return False
def expected_mhz_for_ndiv(arch: str, ndiv: int) -> float:
return round(ndiv * STEP_MHZ_BY_ARCH.get(arch, 13.5), 1)
def clock_matches_expected(
arch: str,
ndiv: int,
measured_mhz: Optional[float],
*,
tolerance_mhz: Optional[float] = None,
) -> Tuple[bool, str]:
"""Verifies that measured hardware memory clock matches the requested NDIV within tolerance."""
expected = expected_mhz_for_ndiv(arch, ndiv)
tol = clock_tolerance_mhz(arch) if tolerance_mhz is None else tolerance_mhz
if measured_mhz is None or not math.isfinite(measured_mhz):
return (
False,
f"hardware memory clock readback unavailable; cannot verify NDIV {ndiv} ({expected:.1f} MHz) applied",
)
if abs(measured_mhz - expected) > tol:
return (
False,
f"measured memory clock {measured_mhz:.1f} MHz does not match requested NDIV {ndiv} "
f"({expected:.1f} +/- {tol:.1f} MHz); parameter may be load-time-only, dropped mid-soak, or rejected",
)
return True, ""
def verify_all_sample_clocks(
arch: str,
ndiv: int,
samples: Sequence[EccSample],
*,
tolerance_mhz: Optional[float] = None,
) -> Tuple[bool, str]:
"""Requires every recorded telemetry sample's memory clock to match the requested NDIV rung."""
for idx, sample in enumerate(samples):
ok, msg = clock_matches_expected(
arch, ndiv, sample.mem_clock_mhz, tolerance_mhz=tolerance_mhz
)
if not ok:
return False, f"sample #{idx}: {msg}"
return True, ""
def verify_live_reference_clocks(
arch: str,
samples: Sequence[EccSample],
*,
tolerance_mhz: Optional[float] = None,
) -> Tuple[bool, str]:
"""Verifies `--no-sysfs` live-clock stability against the first valid clock sample."""
if not samples:
return False, "no telemetry samples recorded for live clock verification"
tol = clock_tolerance_mhz(arch) if tolerance_mhz is None else tolerance_mhz
ref_mhz = samples[0].mem_clock_mhz
if ref_mhz is None or not math.isfinite(ref_mhz):
return False, "initial hardware memory clock readback unavailable in --no-sysfs mode"
for idx, sample in enumerate(samples):
cur = sample.mem_clock_mhz
if cur is None or not math.isfinite(cur):
return False, f"sample #{idx}: hardware memory clock readback unavailable in --no-sysfs mode"
if abs(cur - ref_mhz) > tol:
return (
False,
f"sample #{idx}: live memory clock drifted to {cur:.1f} MHz "
f"(reference {ref_mhz:.1f} +/- {tol:.1f} MHz)",
)
return True, ""
def _parse_effective_cuda_visible_devices(env_val: str) -> List[str]:
"""Parses `CUDA_VISIBLE_DEVICES` following CUDA's truncation-at-first-invalid-token rule.
Per the CUDA programming guide, entries are parsed left-to-right and enumeration stops
at the first invalid/negative token (e.g. `0,-1,1` exposes only `["0"]`, while `2,1`
exposes `["2", "1"]`).
"""
visible: List[str] = []
seen = set()
for raw in env_val.split(","):
tok = raw.strip()
if not tok:
break
if tok.startswith(("GPU-", "MIG-")):
if tok not in seen:
visible.append(tok)
seen.add(tok)
continue
try:
idx = int(tok, 10)
except ValueError:
break
if idx < 0:
break
norm = str(idx)
if norm not in seen:
visible.append(norm)
seen.add(norm)
return visible
def resolve_nvidia_smi_id(
gpu_index: int,
*,
cuda_visible_devices: Optional[str] = None,
cuda_device_uuid: Optional[str] = None,
cuda_pci_bus_id: Optional[str] = None,
) -> str:
"""Resolves a CUDA device index to an unambiguous `nvidia-smi --id=` identifier."""
if gpu_index < 0:
raise ValueError(f"gpu_index must be non-negative, got {gpu_index}")
env_val = os.environ.get("CUDA_VISIBLE_DEVICES") if cuda_visible_devices is None else cuda_visible_devices
if env_val is not None:
visible = _parse_effective_cuda_visible_devices(env_val)
if gpu_index >= len(visible):
raise ValueError(
f"CUDA GPU index {gpu_index} out of range for effective CUDA_VISIBLE_DEVICES={env_val!r} "
f"(visible={visible})"
)
if cuda_pci_bus_id:
return cuda_pci_bus_id.strip()
if cuda_device_uuid:
raw = str(cuda_device_uuid).strip()
return raw if raw.startswith("GPU-") else f"GPU-{raw}"
return visible[gpu_index]
if cuda_pci_bus_id:
return cuda_pci_bus_id.strip()
if cuda_device_uuid:
raw = str(cuda_device_uuid).strip()
return raw if raw.startswith("GPU-") else f"GPU-{raw}"
return str(gpu_index)
def resolve_live_nvidia_smi_id(gpu_index: int) -> str:
"""Resolves physical GPU identity for `nvidia-smi --id=`, preferring PyTorch CUDA UUID when available."""
cuda_uuid: Optional[str] = None
try:
import torch # type: ignore
if torch.cuda.is_available() and 0 <= gpu_index < torch.cuda.device_count():
props = torch.cuda.get_device_properties(gpu_index)
raw_uuid = getattr(props, "uuid", None)
if raw_uuid is not None:
cuda_uuid = str(raw_uuid)
except Exception:
cuda_uuid = None
return resolve_nvidia_smi_id(gpu_index, cuda_device_uuid=cuda_uuid)
def evaluate_gate(
*,
arch: str,
ndiv: Optional[int],
sweeps: int,
max_temp_c: int,
ecc_before: EccSample,
ecc_after: EccSample,
byte_mismatches: int,
digests: Sequence[str] = (),
fp16_digests: Sequence[str] = (),
fp32_digests: Sequence[str] = (),
reference_fp16_digest: Optional[str] = None,
reference_fp32_digest: Optional[str] = None,
workload_rc: int = 0,
negative_control_ok: bool = True,
clock_verified: Optional[bool] = None,
clock_note: str = "",
extra_samples: Sequence[EccSample] = (),
extra_notes: Sequence[str] = (),
checks_run: Sequence[str] = (),
workload_gpu_verified: Optional[bool] = None,
require_workload_gpu_verified: bool = False,
) -> SweepOutcome:
"""Pure, deterministic fail-closed qualification gate evaluator."""
all_samples = [ecc_before, *extra_samples, ecc_after]
measured_mhz = next(
(
s.mem_clock_mhz
for s in reversed(all_samples)
if s.mem_clock_mhz is not None and math.isfinite(s.mem_clock_mhz)
),
None,
)
mhz: Optional[float] = expected_mhz_for_ndiv(arch, ndiv) if ndiv is not None else measured_mhz
gpu_temps = [s.gpu_temp_c for s in all_samples if s.gpu_temp_c is not None]
mem_temps = [s.mem_temp_c for s in all_samples if s.mem_temp_c is not None]
peak_gpu: Optional[int] = max(gpu_temps) if gpu_temps else None
peak_mem: Optional[int] = max(mem_temps) if mem_temps else None
telemetry_ok = all(
s.available and s.sec_total is not None and s.ded_total is not None and s.gpu_temp_c is not None
for s in all_samples
)
# Track whether an initially working HBM temperature sensor stopped reporting mid-soak.
mem_temp_lost = False
seen_mem_temp = False
for sample in all_samples:
if sample.mem_temp_c is not None:
seen_mem_temp = True
elif seen_mem_temp:
mem_temp_lost = True
break
sec_delta = 0
ded_delta = 0
ecc_continuity_lost = False
if telemetry_ok:
for prev, cur in zip(all_samples, all_samples[1:]):
assert prev.sec_total is not None and cur.sec_total is not None
assert prev.ded_total is not None and cur.ded_total is not None
if cur.sec_total < prev.sec_total or cur.ded_total < prev.ded_total:
ecc_continuity_lost = True
break
sec_delta += cur.sec_total - prev.sec_total
ded_delta += cur.ded_total - prev.ded_total
# If the caller requested clock verification on a specific NDIV, require EVERY recorded
# sample across the soak to match that rung (rejecting mid-soak clock drops).
effective_clock_verified = clock_verified
effective_clock_note = clock_note
if effective_clock_verified is True and ndiv is not None:
all_clks_ok, all_clks_msg = verify_all_sample_clocks(arch, ndiv, all_samples)
if not all_clks_ok:
effective_clock_verified = False
effective_clock_note = all_clks_msg
notes: List[str] = list(extra_notes)
fp16_drifted = len(set(fp16_digests)) > 1 or (
reference_fp16_digest is not None
and any(d != reference_fp16_digest for d in fp16_digests)
)
fp32_drifted = len(set(fp32_digests)) > 1 or (
reference_fp32_digest is not None
and any(d != reference_fp32_digest for d in fp32_digests)
)
legacy_drifted = len(set(digests)) > 1
fp16_unverifiable = len(fp16_digests) == 1 and reference_fp16_digest is None
fp32_unverifiable = len(fp32_digests) == 1 and reference_fp32_digest is None
legacy_unverifiable = len(digests) == 1
thermal_exceeded = (peak_gpu is not None and peak_gpu > max_temp_c) or (
peak_mem is not None and peak_mem > max_temp_c
)
if not negative_control_ok:
notes.append("negative-control 1-bit flip canary failed to trigger")
verdict = "FAIL_NEGATIVE_CONTROL"
elif not telemetry_ok:
errs = [s.error for s in all_samples if s.error]
detail = "; ".join(dict.fromkeys(errs)) if errs else "required ECC/temperature telemetry unavailable"
notes.append(f"fail-closed: {detail}")
verdict = "FAIL_TELEMETRY_UNAVAILABLE"
elif mem_temp_lost:
notes.append("fail-closed: HBM memory temperature sensor stopped reporting mid-soak")
verdict = "FAIL_TELEMETRY_UNAVAILABLE"
elif ecc_continuity_lost:
notes.append("fail-closed: volatile ECC counter decreased mid-soak (lost counter continuity)")
verdict = "FAIL_TELEMETRY_UNAVAILABLE"
elif effective_clock_verified is False:
notes.append(effective_clock_note or "requested HBM clock did not apply on hardware")
if thermal_exceeded:
notes.append(f"temperature exceeded ceiling {max_temp_c}C (gpu={peak_gpu}C, mem={peak_mem}C)")
verdict = "FAIL_CLOCK_UNAPPLIED"
elif thermal_exceeded:
notes.append(f"temperature exceeded ceiling {max_temp_c}C (gpu={peak_gpu}C, mem={peak_mem}C)")
verdict = "FAIL_THERMAL"
elif byte_mismatches > 0:
notes.append(f"detected {byte_mismatches} mismatched VRAM byte(s)")
verdict = "FAIL_BYTE_COMPARE"
elif sec_delta > 0 or ded_delta > 0:
notes.append(f"ECC incremented during soak (SEC +{sec_delta}, DED +{ded_delta})")
verdict = "FAIL_ECC_DELTA"
elif fp16_drifted or fp32_drifted or legacy_drifted:
if fp16_drifted:
notes.append(f"FP16 GEMM digest drifted across sweeps or against baseline: {list(fp16_digests)}")
if fp32_drifted:
notes.append(f"FP32 GEMM digest drifted across sweeps or against baseline: {list(fp32_digests)}")
if legacy_drifted:
notes.append(f"GEMM digest drifted across sweeps: {list(digests)}")
verdict = "FAIL_DIGEST"
elif workload_rc != 0:
notes.append(f"workload exited non-zero ({workload_rc})")
verdict = "FAIL_WORKLOAD"
elif fp16_unverifiable or fp32_unverifiable or legacy_unverifiable:
notes.append(
"single GEMM sweep without a pre-tuning baseline reference digest cannot detect drift "
"(use --sweeps >= 2 or supply a baseline reference digest)"
)
verdict = "FAIL_DIGEST"
elif require_workload_gpu_verified and workload_gpu_verified is not True:
notes.append("required GPU compute activity was not verified for workload-only rung")
verdict = "FAIL_WORKLOAD_UNVERIFIED"
else:
verdict = "PASS"
fp16_first = fp16_digests[0] if fp16_digests else ""
fp32_first = fp32_digests[0] if fp32_digests else ""
if digests:
combined_digest = digests[0]
elif fp16_first or fp32_first:
combined_digest = f"fp16:{fp16_first}|fp32:{fp32_first}"
else:
combined_digest = ""
return SweepOutcome(
ndiv=ndiv,
mhz=mhz,
verdict=verdict,
sweeps_completed=sweeps,
mismatched_bytes=byte_mismatches,
sec_delta=sec_delta,
ded_delta=ded_delta,
peak_gpu_temp_c=peak_gpu,
peak_mem_temp_c=peak_mem,
measured_mem_clock_mhz=measured_mhz,
gemm_digest=combined_digest,
fp16_digest=fp16_first,
fp32_digest=fp32_first,
thermal_exceeded=thermal_exceeded,
workload_gpu_verified=workload_gpu_verified,
checks_run=list(checks_run),
notes=notes,
)
def select_highest_clean_rung(
ladder: Sequence[int],
probe_fn: Callable[[int], SweepOutcome],
*,
history: Optional[List[SweepOutcome]] = None,
) -> Tuple[Optional[int], List[SweepOutcome]]:
"""Walks a descending NDIV ladder and returns `(highest_passing_ndiv, history)`.
When `history` is provided by the caller, each completed outcome is appended before
probing the next rung so partial progress is preserved if a subsequent probe raises.
Aborts immediately if `FAIL_THERMAL` or any recorded over-temperature (`thermal_exceeded`)
occurs so an overheated card is not stressed further.
"""
out_history: List[SweepOutcome] = history if history is not None else []
for ndiv in sorted(set(ladder), reverse=True):
outcome = probe_fn(ndiv)
out_history.append(outcome)
if outcome.verdict == "PASS":
return ndiv, out_history
if outcome.verdict == "FAIL_THERMAL" or outcome.thermal_exceeded:
return None, out_history
return None, out_history
def _parse_optional_int(val: str) -> Optional[int]:
try:
return int(val.strip())
except ValueError:
return None
def _parse_optional_float(val: str) -> Optional[float]:
try:
parsed = float(val.strip())
except ValueError:
return None
return parsed if math.isfinite(parsed) else None
def parse_nvidia_smi_csv(line: str) -> EccSample:
"""Parses one CSV row of `sec,ded,gpu_temp,mem_temp,mem_clock_mhz` fail-closed."""
parts = [p.strip() for p in line.strip().split(",")]
if len(parts) < 3:
return EccSample(available=False, error=f"unexpected nvidia-smi CSV output: {line!r}")
sec = _parse_optional_int(parts[0])
ded = _parse_optional_int(parts[1])
gpu_temp = _parse_optional_int(parts[2])
mem_temp = _parse_optional_int(parts[3]) if len(parts) > 3 else None
mem_clk = _parse_optional_float(parts[4]) if len(parts) > 4 else None
missing: List[str] = []
if sec is None:
missing.append("ecc.corrected")
if ded is None:
missing.append("ecc.uncorrected")
if gpu_temp is None:
missing.append("temperature.gpu")
if missing:
return EccSample(
sec_total=sec,
ded_total=ded,
gpu_temp_c=gpu_temp,
mem_temp_c=mem_temp,
mem_clock_mhz=mem_clk,
available=False,
error=f"nvidia-smi missing required telemetry field(s): {', '.join(missing)}",
)
return EccSample(
sec_total=sec,
ded_total=ded,
gpu_temp_c=gpu_temp,
mem_temp_c=mem_temp,
mem_clock_mhz=mem_clk,
available=True,
)
def query_ecc_and_temp_nvidia_smi(gpu_id: Union[int, str]) -> EccSample:
"""Queries volatile ECC counters, temperatures, and memory clock via `nvidia-smi` (fail-closed)."""
smi = shutil.which("nvidia-smi")
if not smi:
return EccSample(available=False, error="nvidia-smi not found in PATH")
cmd = [
smi,
f"--id={gpu_id}",
"--query-gpu=ecc.errors.corrected.volatile.total,ecc.errors.uncorrected.volatile.total,temperature.gpu,temperature.memory,clocks.current.memory",
"--format=csv,noheader,nounits",
]
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
except (OSError, subprocess.SubprocessError) as exc:
return EccSample(available=False, error=f"nvidia-smi execution failed: {exc}")
if proc.returncode != 0 or not proc.stdout.strip():
stderr = proc.stderr.strip() or f"exit status {proc.returncode}"
return EccSample(available=False, error=f"nvidia-smi query failed for --id={gpu_id}: {stderr}")
return parse_nvidia_smi_csv(proc.stdout.strip().splitlines()[0])
_PCI_BDF_FULL_RE = re.compile(r"^([0-9a-fA-F]{1,8}):([0-9a-fA-F]{2}):([0-9a-fA-F]{2})\.([0-7])$")
_PCI_BDF_SHORT_RE = re.compile(r"^([0-9a-fA-F]{2}):([0-9a-fA-F]{2})\.([0-7])$")
def normalize_pci_bdf(raw: str) -> Optional[str]:
"""Normalizes a PCI BDF (`00000000:81:00.0`, `0000:81:00.0`, or `81:00.0`) to `dddd:bb:dd.f`."""
text = raw.strip()
m = _PCI_BDF_FULL_RE.fullmatch(text)
if m:
dom = int(m.group(1), 16)
return f"{dom:04x}:{m.group(2).lower()}:{m.group(3).lower()}.{m.group(4)}"
m = _PCI_BDF_SHORT_RE.fullmatch(text)
if m:
return f"0000:{m.group(1).lower()}:{m.group(2).lower()}.{m.group(3)}"
return None
def query_gpu_pci_bdf_nvidia_smi(gpu_id: Union[int, str]) -> Optional[str]:
"""Queries the normalized PCI BDF for `gpu_id` via `nvidia-smi`."""
smi = shutil.which("nvidia-smi")
if not smi:
return None
cmd = [smi, f"--id={gpu_id}", "--query-gpu=pci.bus_id", "--format=csv,noheader"]
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
except (OSError, subprocess.SubprocessError):
return None
if proc.returncode != 0 or not proc.stdout.strip():
return None
return normalize_pci_bdf(proc.stdout.strip().splitlines()[0])
def parse_ndiv_map(raw: str) -> List[Tuple[str, int]]:
"""Parses a comma-separated `bdf=ndiv` sysfs map preserving entry order."""
entries: List[Tuple[str, int]] = []
for token in raw.strip().split(","):
tok = token.strip()
if not tok:
continue
if "=" not in tok:
continue
bdf_raw, val_raw = tok.split("=", 1)
bdf_norm = normalize_pci_bdf(bdf_raw)
val = _parse_optional_int(val_raw)
if bdf_norm is None or val is None:
continue
entries.append((bdf_norm, val))
return entries
def format_ndiv_map(entries: Sequence[Tuple[str, int]]) -> str:
return ",".join(f"{bdf}={ndiv}" for bdf, ndiv in entries)
def update_ndiv_map_entry(raw: str, target_bdf: str, ndiv: Optional[int]) -> str:
"""Returns updated `bdf=ndiv` map with `target_bdf` set (or removed when `ndiv is None`),
preserving all other GPUs' entries untouched."""
norm_target = normalize_pci_bdf(target_bdf)
if norm_target is None:
raise ValueError(f"invalid PCI BDF: {target_bdf!r}")
kept: List[Tuple[str, int]] = []
replaced = False
for bdf, val in parse_ndiv_map(raw):
if bdf == norm_target:
if ndiv is not None and not replaced:
kept.append((norm_target, ndiv))
replaced = True
continue
kept.append((bdf, val))
if ndiv is not None and not replaced:
kept.append((norm_target, ndiv))
return format_ndiv_map(kept)
def read_sysfs_ndiv_map(map_path: Path) -> Optional[str]:
try:
return map_path.read_text().strip()
except OSError:
return None
def write_sysfs_ndiv_map(map_path: Path, raw: str) -> None:
map_path.write_text(f"{raw}\n")
def read_sysfs_ndiv(param_path: Path) -> Optional[int]:
try:
return int(param_path.read_text().strip())
except (OSError, ValueError):
return None
def write_sysfs_ndiv(param_path: Path, ndiv: int) -> None:
param_path.write_text(f"{ndiv}\n")
def run_cuda_vram_and_gemm_sweep(
gpu_index: int,
chunk_mb: int,
sweeps: int,
*,
per_sweep_telemetry_fn: Optional[Callable[[int], Tuple[EccSample, bool]]] = None,
) -> Tuple[int, List[str], List[str], int, List[EccSample], bool]:
"""Runs full-buffer VRAM pattern sweeps + separate FP16 and FP32 GEMM digest checks via PyTorch.
Returns `(mismatches, fp16_digests, fp32_digests, sweeps_completed, mid_samples, callback_aborted)`.
"""
if sweeps <= 0:
raise ValueError("sweeps must be positive")
if chunk_mb <= 0:
raise ValueError("chunk_mb must be positive")
try:
import torch # type: ignore
except ImportError as exc:
raise RuntimeError(
"PyTorch with CUDA is required for built-in VRAM/GEMM sweeps "
"(or pass --workload '<cmd>' --workload-only, or --self-check)"
) from exc
if not torch.cuda.is_available():
raise RuntimeError("torch.cuda.is_available() is False")
device = torch.device(f"cuda:{gpu_index}")
total_bytes = chunk_mb * 1024 * 1024
total_mismatches = 0
fp16_digests: List[str] = []
fp32_digests: List[str] = []
mid_samples: List[EccSample] = []
sweeps_completed = 0
gen = torch.Generator(device="cpu").manual_seed(0x58017804)
a_cpu_fp16 = torch.randn((1024, 1024), generator=gen, dtype=torch.float16)
b_cpu_fp16 = torch.randn((1024, 1024), generator=gen, dtype=torch.float16)
a_cpu_fp32 = a_cpu_fp16.float()
b_cpu_fp32 = b_cpu_fp16.float()
for sweep_idx in range(sweeps):
for pat in PATTERN_NAMES:
dev_buf = torch.empty(total_bytes, dtype=torch.uint8, device=device)
try:
def _write_chunk(byte_off: int, data: bytes) -> None:
host_t = torch.frombuffer(bytearray(data), dtype=torch.uint8)
dev_buf[byte_off : byte_off + len(data)].copy_(host_t, non_blocking=False)
def _read_chunk(byte_off: int, byte_len: int) -> bytes:
return dev_buf[byte_off : byte_off + byte_len].to("cpu").numpy().tobytes()
mm = verify_full_buffer_chunks(
pat,
total_bytes,
sweep_idx,
_write_chunk,
_read_chunk,
chunk_bytes=DEFAULT_VERIFY_CHUNK_BYTES,
sync_fn=lambda: torch.cuda.synchronize(device),
)
finally:
del dev_buf
total_mismatches += mm
if total_mismatches > 0:
return total_mismatches, fp16_digests, fp32_digests, sweeps_completed, mid_samples, False
# Run genuine FP16 GEMM and FP32 GEMM independently and track both digest streams.
a_dev_fp16 = a_cpu_fp16.to(device)
b_dev_fp16 = b_cpu_fp16.to(device)
c_dev_fp16 = torch.matmul(a_dev_fp16, b_dev_fp16)
torch.cuda.synchronize(device)
fp16_digests.append(hashlib.sha256(c_dev_fp16.to("cpu").numpy().tobytes()).hexdigest())
del a_dev_fp16, b_dev_fp16, c_dev_fp16
a_dev_fp32 = a_cpu_fp32.to(device)
b_dev_fp32 = b_cpu_fp32.to(device)
c_dev_fp32 = torch.matmul(a_dev_fp32, b_dev_fp32)
torch.cuda.synchronize(device)
fp32_digests.append(hashlib.sha256(c_dev_fp32.to("cpu").numpy().tobytes()).hexdigest())
del a_dev_fp32, b_dev_fp32, c_dev_fp32
sweeps_completed += 1
if per_sweep_telemetry_fn is not None:
sample, should_abort = per_sweep_telemetry_fn(sweep_idx)
mid_samples.append(sample)
if should_abort:
return total_mismatches, fp16_digests, fp32_digests, sweeps_completed, mid_samples, True
return total_mismatches, fp16_digests, fp32_digests, sweeps_completed, mid_samples, False
def _run_cuda_sweep_worker(gpu_index: int, chunk_mb: int, result_path: Path) -> int:
"""Child-process entry point executing one isolated VRAM pattern + FP16/FP32 GEMM sweep."""
mm, fp16_list, fp32_list, done, _mids, _aborted = run_cuda_vram_and_gemm_sweep(
gpu_index,
chunk_mb,
1,
per_sweep_telemetry_fn=None,
)
payload = {
"mismatches": mm,
"fp16_digest": fp16_list[0] if fp16_list else "",
"fp32_digest": fp32_list[0] if fp32_list else "",
"sweeps_completed": done,
}
result_path.write_text(json.dumps(payload))
return 0
def run_cuda_sweep_subprocess(
gpu_index: int,
chunk_mb: int,
sweeps: int,
*,
per_sweep_telemetry_fn: Optional[Callable[[int], Tuple[EccSample, bool]]] = None,
timeout_s: float = DEFAULT_SWEEP_TIMEOUT_S,
telemetry_poll_interval_s: float = DEFAULT_TELEMETRY_POLL_INTERVAL_S,
worker_cmd_fn: Optional[Callable[[int, Path], Sequence[str]]] = None,
) -> Tuple[int, List[str], List[str], int, List[EccSample], bool]:
"""Runs each built-in CUDA sweep in an isolated worker subprocess with a hard deadline
and live telemetry polling so a hung GPU kernel/sync or thermal spike never blocks
baseline clock restoration."""
if sweeps <= 0:
raise ValueError("sweeps must be positive")
if chunk_mb <= 0:
raise ValueError("chunk_mb must be positive")
if not math.isfinite(timeout_s) or timeout_s <= 0:
raise ValueError(f"timeout_s must be finite and positive, got {timeout_s}")
total_mismatches = 0
fp16_digests: List[str] = []
fp32_digests: List[str] = []
mid_samples: List[EccSample] = []
sweeps_completed = 0
for sweep_idx in range(sweeps):
with tempfile.TemporaryDirectory(prefix="nvdriver-hbm-sweep-") as td:
res_file = Path(td) / "sweep-result.json"
if worker_cmd_fn is not None:
cmd = list(worker_cmd_fn(sweep_idx, res_file))
else:
cmd = [
sys.executable,
str(Path(__file__).resolve()),
"--_cuda-sweep-worker",
"--gpu",
str(gpu_index),
"--chunk-mb",
str(chunk_mb),
"--_worker-out",
str(res_file),
]
proc = subprocess.Popen(
cmd,
stdout=sys.stderr,
stderr=subprocess.PIPE,
text=True,
start_new_session=True,
)
pgid = proc.pid
deadline = time.monotonic() + timeout_s
next_poll = time.monotonic() + max(0.05, telemetry_poll_interval_s)
aborted_live = False
timed_out = False
try:
while True:
rc = proc.poll()
now = time.monotonic()
if rc is not None:
break
if now >= deadline:
timed_out = True
_reap_process_group(proc, pgid)
break
if per_sweep_telemetry_fn is not None and now >= next_poll:
sample, should_abort = per_sweep_telemetry_fn(sweep_idx)
mid_samples.append(sample)
next_poll = time.monotonic() + max(0.05, telemetry_poll_interval_s)
if should_abort:
aborted_live = True
_reap_process_group(proc, pgid)
break
sleep_for = min(0.1, max(0.0, deadline - time.monotonic()))
if per_sweep_telemetry_fn is not None:
sleep_for = min(sleep_for, max(0.0, next_poll - time.monotonic()))
if sleep_for > 0:
time.sleep(sleep_for)
except BaseException:
_reap_process_group(proc, pgid)
raise
stderr_text = ""
if proc.stderr is not None:
try:
stderr_text = proc.stderr.read().strip()
except OSError:
stderr_text = ""
if aborted_live:
return total_mismatches, fp16_digests, fp32_digests, sweeps_completed, mid_samples, True
if timed_out:
raise TimeoutError(
f"CUDA sweep worker timed out after {timeout_s:.1f}s on sweep #{sweep_idx + 1}"
)
if proc.returncode != 0:
detail = stderr_text or f"exit status {proc.returncode}"
raise RuntimeError(f"CUDA sweep worker failed (rc={proc.returncode}): {detail}")
if not res_file.is_file():
raise RuntimeError("CUDA sweep worker exited 0 without writing result payload")
data = json.loads(res_file.read_text())
mm = int(data.get("mismatches", 0))
total_mismatches += mm
if total_mismatches > 0:
return total_mismatches, fp16_digests, fp32_digests, sweeps_completed, mid_samples, False
fp16_d = str(data.get("fp16_digest", ""))
fp32_d = str(data.get("fp32_digest", ""))
if fp16_d:
fp16_digests.append(fp16_d)
if fp32_d:
fp32_digests.append(fp32_d)
sweeps_completed += 1
if per_sweep_telemetry_fn is not None:
sample, should_abort = per_sweep_telemetry_fn(sweep_idx)
mid_samples.append(sample)
if should_abort:
return total_mismatches, fp16_digests, fp32_digests, sweeps_completed, mid_samples, True
return total_mismatches, fp16_digests, fp32_digests, sweeps_completed, mid_samples, False
def parse_ladder_arg(raw: str) -> List[int]:
"""Parses and validates a comma-separated `--ladder` NDIV list."""
tokens = raw.split(",")
if not tokens:
raise ValueError("--ladder must specify at least one positive NDIV rung")
rungs: List[int] = []
for tok in tokens:
stripped = tok.strip()
if not stripped:
raise ValueError(f"--ladder contains an empty rung in {raw!r}")
try:
val = int(stripped)
except ValueError as exc:
raise ValueError(f"--ladder contains invalid integer {stripped!r} in {raw!r}") from exc
if val <= 0:
raise ValueError(f"--ladder rungs must be positive integers (got {val})")
rungs.append(val)
return rungs
def validate_cli_args(args: argparse.Namespace) -> Optional[str]:
if args.sweeps <= 0:
return f"--sweeps must be a positive integer (got {args.sweeps})"
if not getattr(args, "workload_only", False) and args.sweeps < 2:
return (
f"--sweeps must be >= 2 for built-in GEMM drift detection (got {args.sweeps}); "
"pass --workload-only to run a single external workload sweep"
)
if args.chunk_mb <= 0:
return f"--chunk-mb must be a positive integer (got {args.chunk_mb})"
if args.gpu < 0:
return f"--gpu must be non-negative (got {args.gpu})"
if args.max_temp_c <= 0:
return f"--max-temp-c must be a positive integer (got {args.max_temp_c})"
if args.ndiv is not None and args.ndiv <= 0:
return f"--ndiv must be a positive integer (got {args.ndiv})"
if args.ladder is not None:
try:
parse_ladder_arg(args.ladder)
except ValueError as exc:
return str(exc)
if getattr(args, "workload_only", False) and not getattr(args, "workload", "").strip():
return "--workload-only requires a non-empty --workload command"
wt = getattr(args, "workload_timeout_s", DEFAULT_WORKLOAD_TIMEOUT_S)
if not isinstance(wt, (int, float)) or not math.isfinite(wt) or wt <= 0:
return f"--workload-timeout-s must be a finite positive number (got {wt})"
st = getattr(args, "sweep_timeout_s", DEFAULT_SWEEP_TIMEOUT_S)
if not isinstance(st, (int, float)) or not math.isfinite(st) or st <= 0:
return f"--sweep-timeout-s must be a finite positive number (got {st})"
return None
def default_lock_path(param_path: Path, *, lock_dir: Optional[Path] = None) -> Path:
"""Computes the interprocess lock path for `param_path` independent of `TMPDIR`."""
base_dir = lock_dir if lock_dir is not None else DEFAULT_LOCK_DIR
digest = hashlib.sha256(str(param_path.resolve(strict=False)).encode("utf-8")).hexdigest()[:16]
return base_dir / f"nvdriver-hbm-gate-{digest}.lock"
@contextlib.contextmanager
def sysfs_param_lock(
param_path: Path,
*,
no_sysfs: bool,
lock_dir: Optional[Path] = None,
) -> Iterator[Optional[Path]]:
"""Acquires an interprocess exclusive lock for `param_path` before reading its baseline
and holds it through restore. Live runs always use the fixed `DEFAULT_LOCK_DIR` independent
of `TMPDIR`/`TEMP`/`TMP`; offline tests may inject `lock_dir`. No-op when `no_sysfs` is True."""
if no_sysfs:
yield None
return
lock_path = default_lock_path(param_path, lock_dir=lock_dir)
fd = os.open(str(lock_path), os.O_CREAT | os.O_RDWR, 0o666)
try:
fcntl.flock(fd, fcntl.LOCK_EX)
try:
yield lock_path
finally:
fcntl.flock(fd, fcntl.LOCK_UN)
finally:
os.close(fd)
def parse_pmon_active_compute_pids(pmon_stdout: str) -> List[int]:
"""Parses `nvidia-smi pmon -c 1 -s u` output and returns PIDs with active SM/memory utilization.
A process that merely holds an idle CUDA context reports `sm=0`/`mem=0` (or `-`) and is
NOT treated as actively exercising compute on the GPU.
"""
pids: List[int] = []
for raw in pmon_stdout.splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
parts = line.split()
# Format: gpu pid type sm mem enc dec jpg ofa command
if len(parts) < 5:
continue
pid = _parse_optional_int(parts[1])
proc_type = parts[2].upper()
sm_util = _parse_optional_int(parts[3])
mem_util = _parse_optional_int(parts[4])
if pid is None or pid <= 0 or "C" not in proc_type:
continue
if (sm_util is not None and sm_util > 0) or (mem_util is not None and mem_util > 0):
pids.append(pid)
return pids
def query_gpu_compute_pids_nvidia_smi(gpu_id: Union[int, str]) -> List[int]:
"""Returns PIDs with non-zero SM/memory compute utilization on `gpu_id` via `nvidia-smi pmon`."""
smi = shutil.which("nvidia-smi")
if not smi:
return []
cmd = [smi, "pmon", "-c", "1", "-s", "u", "-i", str(gpu_id)]
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
except (OSError, subprocess.SubprocessError):
return []
if proc.returncode != 0:
return []
return parse_pmon_active_compute_pids(proc.stdout)
def _pid_in_process_group(pid: int, pgid: int) -> bool:
try:
return os.getpgid(pid) == pgid
except OSError:
return False
def _process_group_alive(pgid: int) -> bool:
try:
os.killpg(pgid, 0)
return True
except ProcessLookupError:
return False
except PermissionError:
return True
def _reap_process_group(proc: subprocess.Popen, pgid: int) -> None:
try:
os.killpg(pgid, signal.SIGTERM)
except ProcessLookupError:
pass
try:
proc.wait(timeout=2.0)
except subprocess.TimeoutExpired:
pass
grace_end = time.monotonic() + 2.0
while _process_group_alive(pgid) and time.monotonic() < grace_end:
time.sleep(0.05)
if _process_group_alive(pgid) or proc.poll() is None:
try:
os.killpg(pgid, signal.SIGKILL)
except ProcessLookupError:
pass
if proc.poll() is None:
proc.wait()
kill_end = time.monotonic() + 2.0
while _process_group_alive(pgid) and time.monotonic() < kill_end:
time.sleep(0.05)
def run_workload_command(
cmd: str,
*,
timeout_s: float = DEFAULT_WORKLOAD_TIMEOUT_S,
smi_id: Optional[str] = None,
check_gpu_pids_fn: Optional[Callable[[], Sequence[int]]] = None,
live_telemetry_check_fn: Optional[Callable[[], Tuple[EccSample, bool]]] = None,
telemetry_poll_interval_s: float = DEFAULT_TELEMETRY_POLL_INTERVAL_S,
telemetry_samples_out: Optional[List[EccSample]] = None,
stdout_stream: object = None,
) -> Tuple[int, bool]:
"""Runs an external workload in its own process group with a strict timeout and live
telemetry polling.
Redirects workload stdout to `sys.stderr` (or `stdout_stream`) so stdout stays pure JSON.
Polls `live_telemetry_check_fn()` while running and immediately reaps the process group
(returning rc 125) if thermal, ECC, or clock limits are tripped mid-run.
Waits for both the leader and all same-group descendants to finish before returning so
final telemetry/restoration never races background GPU workers.
Returns `(returncode, gpu_exercised)` where `gpu_exercised` is True only if a PID in the
workload's process group was observed with active compute utilization on `smi_id`.
"""
env = dict(os.environ)
if smi_id is not None:
env["CUDA_VISIBLE_DEVICES"] = smi_id
env["NV_HBM_GATE_GPU_ID"] = smi_id
out_target = sys.stderr if stdout_stream is None else stdout_stream
proc = subprocess.Popen(
cmd,
shell=True,
stdout=out_target,
start_new_session=True,
env=env,
)
pgid = proc.pid
deadline = time.monotonic() + timeout_s
poll_step = max(0.05, telemetry_poll_interval_s)
next_telemetry_poll = time.monotonic() + poll_step
gpu_verified = False
pid_query = check_gpu_pids_fn
if pid_query is None and smi_id is not None:
pid_query = lambda: query_gpu_compute_pids_nvidia_smi(smi_id) # noqa: E731
def _poll_gpu_usage() -> bool:
if pid_query is None:
return False
for pid in pid_query():
if pid == proc.pid or _pid_in_process_group(pid, pgid):
return True
return False
leader_rc: Optional[int] = None
try:
while True:
if not gpu_verified and pid_query is not None:
if _poll_gpu_usage():
gpu_verified = True
if leader_rc is None:
leader_rc = proc.poll()
now = time.monotonic()
remaining = deadline - now
if remaining <= 0:
_reap_process_group(proc, pgid)
return 124, gpu_verified
if live_telemetry_check_fn is not None and now >= next_telemetry_poll:
sample, should_abort = live_telemetry_check_fn()
if telemetry_samples_out is not None:
telemetry_samples_out.append(sample)
next_telemetry_poll = time.monotonic() + poll_step
if should_abort:
_reap_process_group(proc, pgid)
return 125, gpu_verified
if leader_rc is not None and not _process_group_alive(pgid):
return leader_rc, gpu_verified
sleep_for = min(0.1, remaining)
if live_telemetry_check_fn is not None:
sleep_for = min(sleep_for, max(0.0, next_telemetry_poll - time.monotonic()))
if sleep_for > 0:
time.sleep(sleep_for)
except BaseException:
try:
os.killpg(pgid, signal.SIGKILL)
except ProcessLookupError:
pass
try:
proc.wait(timeout=2.0)
except subprocess.TimeoutExpired:
pass
raise
def _normalize_workload_result(res: Union[int, Tuple[int, bool]]) -> Tuple[int, bool]:
if isinstance(res, tuple):
return int(res[0]), bool(res[1])
return int(res), False
def _invoke_workload(
run_workload_fn: Callable[..., Union[int, Tuple[int, bool]]],
cmd: str,
live_check: Callable[[], Tuple[EccSample, bool]],
samples_out: List[EccSample],
) -> Tuple[int, bool]:
"""Calls `run_workload_fn`, passing live telemetry hooks when supported by the callable."""
try:
res = run_workload_fn(
cmd,
live_telemetry_check_fn=live_check,
telemetry_samples_out=samples_out,
)
except TypeError:
res = run_workload_fn(cmd)
return _normalize_workload_result(res)
def run_rung_probe(
*,
arch: str,
gpu: int,
ndiv: Optional[int],
sweeps: int,
chunk_mb: int,
max_temp_c: int,
no_sysfs: bool,
workload: str = "",
workload_only: bool = False,
reference_fp16_digest: Optional[str] = None,
reference_fp32_digest: Optional[str] = None,
write_ndiv_fn: Callable[[int], None],
sleep_fn: Callable[[float], None],
query_telemetry_fn: Callable[[], EccSample],
run_sweep_fn: Callable[
[int, int, int, Callable[[int], Tuple[EccSample, bool]]],
Tuple[int, List[str], List[str], int, List[EccSample], bool],
],
run_workload_fn: Callable[..., Union[int, Tuple[int, bool]]],
) -> SweepOutcome:
"""Executes one rung qualification probe with full pre/mid/post telemetry & clock checks."""
clock_verified: Optional[bool] = None
clock_note = ""
extra_notes: List[str] = []
checks_run: List[str] = []
if not no_sysfs and ndiv is not None:
write_ndiv_fn(ndiv)
sleep_fn(0.25)
else:
extra_notes.append("--no-sysfs mode qualified current live clock; NDIV recommendation omitted")
ecc_before = query_telemetry_fn()
if not ecc_before.available:
return evaluate_gate(
arch=arch,
ndiv=None if no_sysfs else ndiv,
sweeps=0,
max_temp_c=max_temp_c,
ecc_before=ecc_before,
ecc_after=ecc_before,
byte_mismatches=0,
negative_control_ok=True,
extra_notes=extra_notes,
checks_run=checks_run,
)
live_ref_mhz: Optional[float] = None
if not no_sysfs and ndiv is not None:
clock_verified, clock_note = clock_matches_expected(arch, ndiv, ecc_before.mem_clock_mhz)
if not clock_verified:
return evaluate_gate(
arch=arch,
ndiv=ndiv,
sweeps=0,
max_temp_c=max_temp_c,
ecc_before=ecc_before,
ecc_after=ecc_before,
byte_mismatches=0,
negative_control_ok=True,
clock_verified=False,
clock_note=clock_note,
extra_notes=extra_notes,
checks_run=checks_run,
)
else:
clock_verified, clock_note = verify_live_reference_clocks(arch, [ecc_before])
if not clock_verified:
return evaluate_gate(
arch=arch,
ndiv=None,
sweeps=0,
max_temp_c=max_temp_c,
ecc_before=ecc_before,
ecc_after=ecc_before,
byte_mismatches=0,
negative_control_ok=True,
clock_verified=False,
clock_note=clock_note,
extra_notes=extra_notes,
checks_run=checks_run,
)
live_ref_mhz = ecc_before.mem_clock_mhz
if exceeds_thermal_ceiling(ecc_before, max_temp_c):
return evaluate_gate(
arch=arch,
ndiv=None if no_sysfs else ndiv,
sweeps=0,
max_temp_c=max_temp_c,
ecc_before=ecc_before,
ecc_after=ecc_before,
byte_mismatches=0,
negative_control_ok=True,
clock_verified=clock_verified,
extra_notes=extra_notes,
checks_run=checks_run,
)
prev_sample = ecc_before
had_mem_temp = ecc_before.mem_temp_c is not None
live_tol = clock_tolerance_mhz(arch)
def _mid_sweep_check(_sweep_idx: int) -> Tuple[EccSample, bool]:
nonlocal prev_sample, had_mem_temp
sample = query_telemetry_fn()
if not sample.available or exceeds_thermal_ceiling(sample, max_temp_c):
return sample, True
if sample.mem_temp_c is not None:
had_mem_temp = True
elif had_mem_temp:
return sample, True
if not no_sysfs and ndiv is not None:
clk_ok, _ = clock_matches_expected(arch, ndiv, sample.mem_clock_mhz)
if not clk_ok:
return sample, True
elif live_ref_mhz is not None:
if (
sample.mem_clock_mhz is None
or not math.isfinite(sample.mem_clock_mhz)
or abs(sample.mem_clock_mhz - live_ref_mhz) > live_tol
):
return sample, True
assert prev_sample.sec_total is not None and prev_sample.ded_total is not None
assert sample.sec_total is not None and sample.ded_total is not None
if sample.sec_total != prev_sample.sec_total or sample.ded_total != prev_sample.ded_total:
prev_sample = sample
return sample, True
prev_sample = sample
return sample, False
mismatches = 0
fp16_digests: List[str] = []
fp32_digests: List[str] = []
mid_samples: List[EccSample] = []
sweeps_done = 0
workload_rc = 0
workload_gpu_verified: Optional[bool] = None
def _live_workload_check() -> Tuple[EccSample, bool]:
return _mid_sweep_check(len(mid_samples))
if workload_only:
checks_run.append("workload_only")
extra_notes.append("--workload-only mode ran external workload with telemetry/clock/ECC checks (PyTorch sweeps skipped)")
workload_gpu_verified = True
for sweep_idx in range(sweeps):
workload_rc, gpu_used = _invoke_workload(
run_workload_fn, workload, _live_workload_check, mid_samples
)
if not gpu_used:
workload_gpu_verified = False
sweeps_done += 1
sample, should_abort = _mid_sweep_check(sweep_idx)
mid_samples.append(sample)
if workload_rc != 0 or should_abort:
break
if not workload_gpu_verified:
extra_notes.append(
"workload-only command did not produce verified compute activity on target GPU; "
"NDIV recommendation and live_clock_qualified withheld"
)
else:
checks_run.extend(["vram_patterns", "fp16_gemm", "fp32_gemm"])
(
mismatches,
fp16_digests,
fp32_digests,
sweeps_done,
mid_samples,
callback_aborted,
) = run_sweep_fn(gpu, chunk_mb, sweeps, _mid_sweep_check)
aborted_early = (
callback_aborted
or sweeps_done < sweeps
or any((not s.available) or exceeds_thermal_ceiling(s, max_temp_c) for s in mid_samples)
)
if workload and mismatches == 0 and not aborted_early:
checks_run.append("workload")
workload_rc, workload_gpu_verified = _invoke_workload(
run_workload_fn, workload, _live_workload_check, mid_samples
)
ecc_after = query_telemetry_fn()
all_samples = [ecc_before, *mid_samples, ecc_after]
if all(s.available for s in all_samples) and clock_verified:
if not no_sysfs and ndiv is not None:
clock_verified, clock_note = verify_all_sample_clocks(arch, ndiv, all_samples)
else:
clock_verified, clock_note = verify_live_reference_clocks(arch, all_samples)
return evaluate_gate(
arch=arch,
ndiv=None if no_sysfs else ndiv,
sweeps=sweeps_done,
max_temp_c=max_temp_c,
ecc_before=ecc_before,
ecc_after=ecc_after,
byte_mismatches=mismatches,
fp16_digests=fp16_digests,
fp32_digests=fp32_digests,
reference_fp16_digest=reference_fp16_digest,
reference_fp32_digest=reference_fp32_digest,
workload_rc=workload_rc,
negative_control_ok=True,
clock_verified=clock_verified,
clock_note=clock_note,
extra_samples=mid_samples,
extra_notes=extra_notes,
checks_run=checks_run,
workload_gpu_verified=workload_gpu_verified,
require_workload_gpu_verified=workload_only,
)
def run_self_check() -> int:
"""Offline unit test suite (zero GPU or sysfs access; enforced even under `python3 -O`)."""
# 1. Pattern generation & negative control must catch a 1-bit flip.
_check(run_negative_control(512), "negative control must detect 1-bit flip")
for pat in PATTERN_NAMES:
buf = generate_pattern_bytes(pat, 64, seed_offset=7)
_check(len(buf) == 256, "pattern byte length mismatch")
_check(compare_buffers(buf, buf) == (0, None), "identical buffer comparison failed")
# 2. Full-buffer chunked verifier detects a 1-bit flip well past the first chunk.
backing = bytearray(1024)
_check(
verify_full_buffer_chunks(
"addr_xor",
1024,
sweep_idx=2,
write_chunk=lambda off, b: backing.__setitem__(slice(off, off + len(b)), b),
read_chunk=lambda off, n: bytes(backing[off : off + n]),
chunk_bytes=256,
)
== 0,
"clean full-buffer chunked verification should pass",
)
def _corrupt_last_chunk() -> None:
backing[-1] ^= 0x80
_check(
verify_full_buffer_chunks(
"addr_xor",
1024,
sweep_idx=2,
write_chunk=lambda off, b: backing.__setitem__(slice(off, off + len(b)), b),
read_chunk=lambda off, n: bytes(backing[off : off + n]),
chunk_bytes=256,
sync_fn=_corrupt_last_chunk,
)
== 1,
"full-buffer chunked verification must detect corruption in final chunk",
)
# 3. Clean pass verdict with both FP16 and FP32 digests and valid telemetry.
good_before = EccSample(sec_total=0, ded_total=0, gpu_temp_c=45, mem_temp_c=52, mem_clock_mhz=1890.0)
good_after = EccSample(sec_total=0, ded_total=0, gpu_temp_c=68, mem_temp_c=74, mem_clock_mhz=1890.0)
ok = evaluate_gate(
arch="ga100",
ndiv=70,
sweeps=3,
max_temp_c=85,
ecc_before=good_before,
ecc_after=good_after,
byte_mismatches=0,
fp16_digests=["f16a", "f16a", "f16a"],
fp32_digests=["f32b", "f32b", "f32b"],
workload_rc=0,
negative_control_ok=True,
clock_verified=True,
)
_check(ok.verdict == "PASS" and ok.mhz == 1890.0, f"expected PASS @ 1890.0, got {ok}")
# 4. Fail-closed checks: negative control, unavailable telemetry, unapplied clock,
# byte mismatch, ECC delta, FP16/FP32 digest drift, thermal, workload.
base_ok = EccSample(sec_total=0, ded_total=0, gpu_temp_c=50, mem_temp_c=55, mem_clock_mhz=1107.0)
_check(
evaluate_gate(
arch="gv100",
ndiv=82,
sweeps=1,
max_temp_c=85,
ecc_before=base_ok,
ecc_after=base_ok,
byte_mismatches=0,
fp16_digests=["a"],
fp32_digests=["b"],
negative_control_ok=False,
).verdict
== "FAIL_NEGATIVE_CONTROL",
"negative control failure must fail closed",
)
_check(
evaluate_gate(
arch="gv100",
ndiv=82,
sweeps=1,
max_temp_c=85,
ecc_before=EccSample(available=False, error="nvidia-smi not found"),
ecc_after=base_ok,
byte_mismatches=0,
fp16_digests=["a"],
fp32_digests=["b"],
).verdict
== "FAIL_TELEMETRY_UNAVAILABLE",
"unavailable telemetry must fail closed instead of defaulting to zero",
)
_check(
not parse_nvidia_smi_csv("[N/A], 0, 55, [N/A], 877").available,
"N/A ECC counters must mark sample unavailable",
)
_check(
parse_nvidia_smi_csv("0, 0, 55, [N/A], 877").available,
"valid ECC + gpu temp with missing mem temp should remain available",
)
clk_ok, clk_msg = clock_matches_expected("gp100", 62, 715.0)
_check(not clk_ok and "715.0" in clk_msg, "unchanged clock must fail verification")
_check(clock_matches_expected("gp100", 62, 837.0)[0], "matching clock must verify")
_check(
evaluate_gate(
arch="gp100",
ndiv=62,
sweeps=0,
max_temp_c=85,
ecc_before=base_ok,
ecc_after=base_ok,
byte_mismatches=0,
clock_verified=False,
clock_note=clk_msg,
).verdict
== "FAIL_CLOCK_UNAPPLIED",
"unapplied clock must return FAIL_CLOCK_UNAPPLIED",
)
_check(
evaluate_gate(
arch="gp100",
ndiv=62,
sweeps=1,
max_temp_c=85,
ecc_before=base_ok,
ecc_after=base_ok,
byte_mismatches=1,
fp16_digests=["a"],
fp32_digests=["b"],
).verdict
== "FAIL_BYTE_COMPARE",
"byte mismatch must fail",
)
_check(
evaluate_gate(
arch="gv100",
ndiv=80,
sweeps=2,
max_temp_c=85,
ecc_before=EccSample(sec_total=4, ded_total=0, gpu_temp_c=50),
ecc_after=EccSample(sec_total=5, ded_total=0, gpu_temp_c=60),
byte_mismatches=0,
fp16_digests=["a", "a"],
fp32_digests=["b", "b"],
).verdict
== "FAIL_ECC_DELTA",
"ECC increment must fail",
)
_check(
evaluate_gate(
arch="ga100",
ndiv=74,
sweeps=2,
max_temp_c=85,
ecc_before=base_ok,
ecc_after=base_ok,
byte_mismatches=0,
fp16_digests=["deadbeef", "cafebabe"],
fp32_digests=["same", "same"],
).verdict
== "FAIL_DIGEST",
"FP16 GEMM digest drift must fail independently of FP32",
)
_check(
evaluate_gate(
arch="ga100",
ndiv=74,
sweeps=2,
max_temp_c=85,
ecc_before=base_ok,
ecc_after=base_ok,
byte_mismatches=0,
fp16_digests=["same", "same"],
fp32_digests=["1111", "2222"],
).verdict
== "FAIL_DIGEST",
"FP32 GEMM digest drift must fail independently of FP16",
)
_check(
evaluate_gate(
arch="ga100",
ndiv=70,
sweeps=1,
max_temp_c=80,
ecc_before=EccSample(sec_total=0, ded_total=0, gpu_temp_c=60, mem_temp_c=70),
ecc_after=EccSample(sec_total=0, ded_total=0, gpu_temp_c=72, mem_temp_c=83),
byte_mismatches=0,
fp16_digests=["a"],
fp32_digests=["b"],
).verdict
== "FAIL_THERMAL",
"thermal ceiling breach must fail",
)
_check(
evaluate_gate(
arch="gv100",
ndiv=78,
sweeps=1,
max_temp_c=85,
ecc_before=base_ok,
ecc_after=base_ok,
byte_mismatches=0,
fp16_digests=["a"],
fp32_digests=["b"],
workload_rc=2,
).verdict
== "FAIL_WORKLOAD",
"nonzero workload must fail",
)
# 5. CUDA_VISIBLE_DEVICES / UUID resolution for nvidia-smi --id=.
_check(resolve_nvidia_smi_id(0, cuda_visible_devices="3,5") == "3", "CUDA_VISIBLE_DEVICES mapping failed")
_check(resolve_nvidia_smi_id(1, cuda_visible_devices="GPU-abc,GPU-def") == "GPU-def", "UUID mapping failed")
_check(resolve_nvidia_smi_id(0, cuda_device_uuid="1234-5678") == "GPU-1234-5678", "PyTorch UUID prefix failed")
_check(resolve_nvidia_smi_id(0, cuda_pci_bus_id="0000:81:00.0") == "0000:81:00.0", "PCI bus ID mapping failed")
# 6. CLI argument validation rejects nonpositive sweeps/chunk-mb.
_check(validate_cli_args(parse_args(["--sweeps", "0"])) is not None, "--sweeps 0 must be rejected")
_check(validate_cli_args(parse_args(["--sweeps", "-2"])) is not None, "--sweeps -2 must be rejected")
_check(validate_cli_args(parse_args(["--chunk-mb", "0"])) is not None, "--chunk-mb 0 must be rejected")
_check(validate_cli_args(parse_args(["--sweeps", "2", "--chunk-mb", "64"])) is None, "valid args must pass")
# 7. Descending ladder selects highest clean rung and aborts immediately on FAIL_THERMAL.
def fake_probe(ndiv: int) -> SweepOutcome:
return evaluate_gate(
arch="gv100",
ndiv=ndiv,
sweeps=2,
max_temp_c=85,
ecc_before=EccSample(sec_total=0, ded_total=0, gpu_temp_c=55),
ecc_after=EccSample(sec_total=1 if ndiv > 74 else 0, ded_total=0, gpu_temp_c=65),
byte_mismatches=0,
fp16_digests=["ok", "ok"],
fp32_digests=["ok", "ok"],
)
best, hist = select_highest_clean_rung(DEFAULT_LADDERS["gv100"], fake_probe)
_check(best == 74, f"expected 74, got {best}")
_check([h.ndiv for h in hist] == [82, 78, 74], f"unexpected ladder history: {hist}")
def hot_probe(ndiv: int) -> SweepOutcome:
return evaluate_gate(
arch="gv100",
ndiv=ndiv,
sweeps=0,
max_temp_c=80,
ecc_before=EccSample(sec_total=0, ded_total=0, gpu_temp_c=88),
ecc_after=EccSample(sec_total=0, ded_total=0, gpu_temp_c=88),
byte_mismatches=0,
)
hot_best, hot_hist = select_highest_clean_rung(DEFAULT_LADDERS["gv100"], hot_probe)
_check(hot_best is None and len(hot_hist) == 1 and hot_hist[0].verdict == "FAIL_THERMAL", "ladder must stop immediately on FAIL_THERMAL")
# 8. --no-sysfs outcome omits unverified NDIV and reports measured MHz.
no_sysfs_ok = evaluate_gate(
arch="gv100",
ndiv=None,
sweeps=2,
max_temp_c=85,
ecc_before=EccSample(sec_total=0, ded_total=0, gpu_temp_c=45, mem_clock_mhz=877.0),
ecc_after=EccSample(sec_total=0, ded_total=0, gpu_temp_c=52, mem_clock_mhz=877.0),
byte_mismatches=0,
fp16_digests=["a", "a"],
fp32_digests=["b", "b"],
)
_check(no_sysfs_ok.verdict == "PASS" and no_sysfs_ok.ndiv is None and no_sysfs_ok.mhz == 877.0, "--no-sysfs must use measured clock and omit NDIV")
# 9. Restoration reports missing parameter path and write OSError instead of swallowing them.
with tempfile.TemporaryDirectory() as td:
td_path = Path(td)
ok_param = td_path / "ndiv"
ok_param.write_text("78\n")
_check(restore_sysfs_ndiv(ok_param, 65, no_sysfs=False) is None, "restore should succeed")
_check(ok_param.read_text().strip() == "65", "restore value mismatch")
_check(restore_sysfs_ndiv(td_path / "missing", 65, no_sysfs=False) is not None, "missing param should error")
_check(restore_sysfs_ndiv(td_path, 65, no_sysfs=False) is not None, "directory write should error")
_check(restore_sysfs_ndiv(ok_param, None, no_sysfs=False) is not None, "missing baseline should error")
_check(restore_sysfs_ndiv(td_path / "missing", 65, no_sysfs=True) is None, "--no-sysfs restore should no-op")
_check(restore_sysfs_ndiv(ok_param, None, no_sysfs=True) is None, "--no-sysfs restore should no-op")
# 10. Per-parameter interprocess lock blocks concurrent access and skips --no-sysfs.
with sysfs_param_lock(ok_param, no_sysfs=False, lock_dir=td_path) as lp:
_check(lp is not None and lp.exists(), "lock file must be created")
probe_fd = os.open(str(lp), os.O_RDWR)
try:
blocked = False
try:
fcntl.flock(probe_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
blocked = True
_check(blocked, "concurrent non-blocking flock must block while lock is held")
finally:
os.close(probe_fd)
with sysfs_param_lock(ok_param, no_sysfs=True, lock_dir=td_path) as lp_noop:
_check(lp_noop is None, "--no-sysfs must not take a lock")
# 11. Adjacent NDIV readbacks are distinguishable (GP100 13.5 MHz step) & NaN clocks rejected.
_check(not clock_matches_expected("gp100", 54, 716.0)[0], "NDIV 53 (716 MHz) must not verify NDIV 54 (729 MHz)")
_check(not clock_matches_expected("gp100", 54, 742.0)[0], "NDIV 55 (742 MHz) must not verify NDIV 54 (729 MHz)")
_check(clock_matches_expected("gp100", 53, 715.0)[0], "715 MHz must verify GP100 NDIV 53 (715.5 MHz)")
_check(clock_matches_expected("gp100", 53, 716.0)[0], "716 MHz must verify GP100 NDIV 53 (715.5 MHz)")
_check(clock_matches_expected("gp100", 54, 729.0)[0], "729 MHz must verify GP100 NDIV 54 (729.0 MHz)")
_check(parse_nvidia_smi_csv("0, 0, 55, 60, nan").mem_clock_mhz is None, "nan clock must parse as None")
_check(parse_nvidia_smi_csv("0, 0, 55, 60, inf").mem_clock_mhz is None, "inf clock must parse as None")
_check(not clock_matches_expected("ga100", 70, float("nan"))[0], "NaN clock must fail verification")
# 12. HBM temperature sensor dropout fails closed while GPU-temp-only cards still pass.
_check(
evaluate_gate(
arch="ga100",
ndiv=70,
sweeps=2,
max_temp_c=85,
ecc_before=EccSample(sec_total=0, ded_total=0, gpu_temp_c=55, mem_temp_c=75, mem_clock_mhz=1890.0),
ecc_after=EccSample(sec_total=0, ded_total=0, gpu_temp_c=60, mem_temp_c=None, mem_clock_mhz=1890.0),
byte_mismatches=0,
fp16_digests=["a", "a"],
fp32_digests=["b", "b"],
clock_verified=True,
).verdict
== "FAIL_TELEMETRY_UNAVAILABLE",
"HBM temp sensor dropout (75C -> N/A) must fail closed",
)
_check(
evaluate_gate(
arch="gp100",
ndiv=62,
sweeps=2,
max_temp_c=85,
ecc_before=EccSample(sec_total=0, ded_total=0, gpu_temp_c=50, mem_temp_c=None, mem_clock_mhz=837.0),
ecc_after=EccSample(sec_total=0, ded_total=0, gpu_temp_c=58, mem_temp_c=None, mem_clock_mhz=837.0),
byte_mismatches=0,
fp16_digests=["a", "a"],
fp32_digests=["b", "b"],
clock_verified=True,
).verdict
== "PASS",
"GPU-temp-only card with no HBM sensor must still pass",
)
# 13. Non-monotonic volatile ECC counter (10 -> 0 -> 1) fails closed; steady (10 -> 10 -> 10) passes.
_check(
evaluate_gate(
arch="ga100",
ndiv=70,
sweeps=2,
max_temp_c=85,
ecc_before=EccSample(sec_total=10, ded_total=0, gpu_temp_c=50, mem_temp_c=60, mem_clock_mhz=1890.0),
extra_samples=[EccSample(sec_total=0, ded_total=0, gpu_temp_c=55, mem_temp_c=65, mem_clock_mhz=1890.0)],
ecc_after=EccSample(sec_total=1, ded_total=0, gpu_temp_c=58, mem_temp_c=68, mem_clock_mhz=1890.0),
byte_mismatches=0,
fp16_digests=["a", "a"],
fp32_digests=["b", "b"],
clock_verified=True,
).verdict
== "FAIL_TELEMETRY_UNAVAILABLE",
"volatile ECC counter decrease (10 -> 0 -> 1) must fail closed",
)
_check(
evaluate_gate(
arch="ga100",
ndiv=70,
sweeps=2,
max_temp_c=85,
ecc_before=EccSample(sec_total=10, ded_total=0, gpu_temp_c=50, mem_temp_c=60, mem_clock_mhz=1890.0),
extra_samples=[EccSample(sec_total=10, ded_total=0, gpu_temp_c=55, mem_temp_c=65, mem_clock_mhz=1890.0)],
ecc_after=EccSample(sec_total=10, ded_total=0, gpu_temp_c=58, mem_temp_c=68, mem_clock_mhz=1890.0),
byte_mismatches=0,
fp16_digests=["a", "a"],
fp32_digests=["b", "b"],
clock_verified=True,
).verdict
== "PASS",
"steady non-zero ECC counters (10 -> 10 -> 10) must pass",
)
# 14. Ladder & workload-only CLI validation rejects malformed inputs before sysfs writes.
_check(validate_cli_args(parse_args(["--ladder", "82,bad"])) is not None, "--ladder 82,bad must be rejected")
_check(validate_cli_args(parse_args(["--ladder", ","])) is not None, "--ladder , must be rejected")
_check(validate_cli_args(parse_args(["--ladder", ""])) is not None, "--ladder '' must be rejected")
_check(validate_cli_args(parse_args(["--ladder", "82,78,74"])) is None, "valid --ladder must pass")
_check(parse_ladder_arg("82,78,74") == [82, 78, 74], "parse_ladder_arg mismatch")
_check(validate_cli_args(parse_args(["--workload-only"])) is not None, "--workload-only requires --workload")
_check(validate_cli_args(parse_args(["--workload-only", "--workload", "true"])) is None, "valid --workload-only must pass")
# 15. Mid-soak clock drop (1890 -> 1836 -> 1890) fails GA100 NDIV 70; steady (1890 -> 1890 -> 1890) passes.
def _run_clock_seq_test(clocks: Sequence[float]) -> Optional[int]:
samples = iter(
[EccSample(sec_total=0, ded_total=0, gpu_temp_c=55, mem_temp_c=65, mem_clock_mhz=c) for c in clocks]
)
def _fake_sweep(
_gpu: int,
_chunk: int,
n_sweeps: int,
cb: Callable[[int], Tuple[EccSample, bool]],
) -> Tuple[int, List[str], List[str], int, List[EccSample], bool]:
mids: List[EccSample] = []
for i in range(n_sweeps):
s, abort = cb(i)
mids.append(s)
if abort:
return 0, ["f16"], ["f32"], i + 1, mids, True
return 0, ["f16"] * n_sweeps, ["f32"] * n_sweeps, n_sweeps, mids, False
best_clk, _ = select_highest_clean_rung(
[70],
lambda nd: run_rung_probe(
arch="ga100",
gpu=0,
ndiv=nd,
sweeps=1,
chunk_mb=64,
max_temp_c=85,
no_sysfs=False,
reference_fp16_digest="f16",
reference_fp32_digest="f32",
write_ndiv_fn=lambda _n: None,
sleep_fn=lambda _s: None,
query_telemetry_fn=lambda: next(samples),
run_sweep_fn=_fake_sweep,
run_workload_fn=lambda _c: 0,
),
)
return best_clk
_check(_run_clock_seq_test([1890.0, 1836.0, 1890.0]) is None, "1890 -> 1836 -> 1890 must not recommend NDIV 70")
_check(_run_clock_seq_test([1890.0, 1890.0, 1890.0]) == 70, "1890 -> 1890 -> 1890 must recommend NDIV 70")
# 16. Final sweep ECC increment on --sweeps 1 skips --workload and reports FAIL_ECC_DELTA.
workload_called = []
ecc_seq = iter(
[
EccSample(sec_total=0, ded_total=0, gpu_temp_c=55, mem_temp_c=65, mem_clock_mhz=1890.0),
EccSample(sec_total=1, ded_total=0, gpu_temp_c=60, mem_temp_c=70, mem_clock_mhz=1890.0),
EccSample(sec_total=1, ded_total=0, gpu_temp_c=60, mem_temp_c=70, mem_clock_mhz=1890.0),
]
)
def _single_sweep_with_cb(
_gpu: int,
_chunk: int,
_n_sweeps: int,
cb: Callable[[int], Tuple[EccSample, bool]],
) -> Tuple[int, List[str], List[str], int, List[EccSample], bool]:
s, abort = cb(0)
return 0, ["f16"], ["f32"], 1, [s], abort
ecc_abort_out = run_rung_probe(
arch="ga100",
gpu=0,
ndiv=70,
sweeps=1,
chunk_mb=64,
max_temp_c=85,
no_sysfs=False,
workload="echo should-not-run",
write_ndiv_fn=lambda _n: None,
sleep_fn=lambda _s: None,
query_telemetry_fn=lambda: next(ecc_seq),
run_sweep_fn=_single_sweep_with_cb,
run_workload_fn=lambda cmd: (workload_called.append(cmd), 0)[1],
)
_check(ecc_abort_out.verdict == "FAIL_ECC_DELTA", f"expected FAIL_ECC_DELTA, got {ecc_abort_out}")
_check(not workload_called, "workload must be skipped when final sweep callback detects ECC increment")
# 17. --workload-only executes external workload without invoking PyTorch sweep and records checks_run.
wo_samples = iter(
[
EccSample(sec_total=0, ded_total=0, gpu_temp_c=50, mem_temp_c=60, mem_clock_mhz=1890.0),
EccSample(sec_total=0, ded_total=0, gpu_temp_c=55, mem_temp_c=65, mem_clock_mhz=1890.0),
EccSample(sec_total=0, ded_total=0, gpu_temp_c=56, mem_temp_c=66, mem_clock_mhz=1890.0),
]
)
wo_runs: List[str] = []
def _forbid_pytorch(*_a: object, **_kw: object) -> Tuple[int, List[str], List[str], int, List[EccSample], bool]:
raise AssertionError("PyTorch sweep must not be called in --workload-only mode")
wo_out = run_rung_probe(
arch="ga100",
gpu=0,
ndiv=70,
sweeps=1,
chunk_mb=64,
max_temp_c=85,
no_sysfs=False,
workload="custom-bench",
workload_only=True,
write_ndiv_fn=lambda _n: None,
sleep_fn=lambda _s: None,
query_telemetry_fn=lambda: next(wo_samples),
run_sweep_fn=_forbid_pytorch,
run_workload_fn=lambda cmd: (wo_runs.append(cmd), (0, False))[1],
)
_check(
wo_out.verdict == "FAIL_WORKLOAD_UNVERIFIED"
and wo_runs == ["custom-bench"]
and wo_out.checks_run == ["workload_only"]
and wo_out.workload_gpu_verified is False,
f"unexpected workload-only unverified outcome: {wo_out}",
)
# 18. Hot sample + clock fault stops ladder immediately; cool clock fault continues to next rung.
hot_clk_best, hot_clk_hist = select_highest_clean_rung(
[70, 67],
lambda nd: evaluate_gate(
arch="ga100",
ndiv=nd,
sweeps=1,
max_temp_c=85,
ecc_before=EccSample(sec_total=0, ded_total=0, gpu_temp_c=60, mem_clock_mhz=1890.0),
extra_samples=[EccSample(sec_total=0, ded_total=0, gpu_temp_c=90, mem_clock_mhz=1836.0)],
ecc_after=EccSample(sec_total=0, ded_total=0, gpu_temp_c=88, mem_clock_mhz=1890.0),
byte_mismatches=0,
clock_verified=True,
),
)
_check(
hot_clk_best is None
and len(hot_clk_hist) == 1
and hot_clk_hist[0].verdict == "FAIL_CLOCK_UNAPPLIED"
and hot_clk_hist[0].thermal_exceeded,
f"hot clock fault must stop ladder immediately, got {hot_clk_hist}",
)
cool_clk_best, cool_clk_hist = select_highest_clean_rung(
[70, 67],
lambda nd: evaluate_gate(
arch="ga100",
ndiv=nd,
sweeps=1,
max_temp_c=85,
ecc_before=EccSample(sec_total=0, ded_total=0, gpu_temp_c=55, mem_clock_mhz=1809.0),
ecc_after=EccSample(sec_total=0, ded_total=0, gpu_temp_c=60, mem_clock_mhz=1809.0),
byte_mismatches=0,
clock_verified=True,
),
)
_check(
cool_clk_best == 67 and len(cool_clk_hist) == 2 and cool_clk_hist[0].verdict == "FAIL_CLOCK_UNAPPLIED",
f"cool clock mismatch should proceed to next rung, got {cool_clk_best} {cool_clk_hist}",
)
# 19. --no-sysfs verifies live clock stability against first sample (steady passes; drift or missing fails).
def _run_no_sysfs_clock_seq(clocks: Sequence[Optional[float]]) -> SweepOutcome:
seq = iter([EccSample(sec_total=0, ded_total=0, gpu_temp_c=55, mem_clock_mhz=c) for c in clocks])
def _clean_sweep(
_gpu: int,
_chunk: int,
_n: int,
cb: Callable[[int], Tuple[EccSample, bool]],
) -> Tuple[int, List[str], List[str], int, List[EccSample], bool]:
s, abort = cb(0)
return 0, ["f16"], ["f32"], 1, [s], abort
return run_rung_probe(
arch="ga100",
gpu=0,
ndiv=None,
sweeps=1,
chunk_mb=64,
max_temp_c=85,
no_sysfs=True,
reference_fp16_digest="f16",
reference_fp32_digest="f32",
write_ndiv_fn=lambda _n: None,
sleep_fn=lambda _s: None,
query_telemetry_fn=lambda: next(seq),
run_sweep_fn=_clean_sweep,
run_workload_fn=lambda _c: (0, False),
)
_check(_run_no_sysfs_clock_seq([1890.0, 1890.0, 1890.0]).verdict == "PASS", "--no-sysfs steady clock must pass")
_check(_run_no_sysfs_clock_seq([1890.0, 1836.0, 1890.0]).verdict == "FAIL_CLOCK_UNAPPLIED", "--no-sysfs mid-soak drift must fail")
_check(_run_no_sysfs_clock_seq([None, None, None]).verdict == "FAIL_CLOCK_UNAPPLIED", "--no-sysfs missing clock must fail")
# 20. Workload timeout reaps process group and redirects stdout away from report stream.
with tempfile.TemporaryFile() as capture_out:
rc_fast, gpu_v = run_workload_command(
"echo workload-noise",
timeout_s=5.0,
stdout_stream=capture_out,
)
capture_out.seek(0)
_check(rc_fast == 0 and not gpu_v and b"workload-noise" in capture_out.read(), "workload stdout redirection failed")
rc_to, _ = run_workload_command("sleep 30", timeout_s=0.15, stdout_stream=subprocess.DEVNULL)
_check(rc_to == 124, f"expected timeout rc 124, got {rc_to}")
# 21. default_lock_path is independent of TMPDIR without acquiring the live /tmp lock.
orig_tmpdir = os.environ.get("TMPDIR")
try:
os.environ["TMPDIR"] = "/nonexistent-tmpdir-a"
lp_a = default_lock_path(Path("/sys/module/nvidia_rs/parameters/v100_hbm_ndiv"))
os.environ["TMPDIR"] = "/nonexistent-tmpdir-b"
lp_b = default_lock_path(Path("/sys/module/nvidia_rs/parameters/v100_hbm_ndiv"))
_check(lp_a == lp_b and lp_a.parent == DEFAULT_LOCK_DIR, "live lock path must ignore TMPDIR")
finally:
if orig_tmpdir is None:
os.environ.pop("TMPDIR", None)
else:
os.environ["TMPDIR"] = orig_tmpdir
# 22. CUDA_VISIBLE_DEVICES stops at first negative/invalid token (e.g. 0,-1,1 -> only 0).
_check(resolve_nvidia_smi_id(0, cuda_visible_devices="0,-1,1") == "0", "0,-1,1 index 0 must resolve to 0")
_check(resolve_nvidia_smi_id(1, cuda_visible_devices="2,1") == "1", "reordered 2,1 index 1 must resolve to 1")
oob_rejected = False
try:
resolve_nvidia_smi_id(1, cuda_visible_devices="0,-1,1")
except ValueError:
oob_rejected = True
_check(oob_rejected, "0,-1,1 index 1 must be rejected")
# 23. pmon parser ignores idle CUDA contexts (sm=0, mem=0) and accepts active compute PIDs.
pmon_sample = (
"# gpu pid type sm mem enc dec jpg ofa command\n"
"# Idx # C/G % % % % % % name\n"
" 0 11111 C 0 0 - - - - idle_ctx\n"
" 0 22222 C - - - - - - idle_dash\n"
" 0 33333 C 42 8 - - - - active_gemm\n"
)
_check(parse_pmon_active_compute_pids(pmon_sample) == [33333], "pmon parser must require active utilization")
# 24. Unverified workload-only rung returns FAIL_WORKLOAD_UNVERIFIED so ladder keeps descending.
unverified_rung = evaluate_gate(
arch="gv100",
ndiv=78,
sweeps=1,
max_temp_c=85,
ecc_before=EccSample(sec_total=0, ded_total=0, gpu_temp_c=45, mem_temp_c=50, mem_clock_mhz=1053.0),
ecc_after=EccSample(sec_total=0, ded_total=0, gpu_temp_c=46, mem_temp_c=51, mem_clock_mhz=1053.0),
byte_mismatches=0,
workload_rc=0,
clock_verified=True,
workload_gpu_verified=False,
require_workload_gpu_verified=True,
)
_check(unverified_rung.verdict == "FAIL_WORKLOAD_UNVERIFIED", f"expected FAIL_WORKLOAD_UNVERIFIED, got {unverified_rung.verdict}")
# 25. Workload runner enforces deadline even when PID poll blocks past deadline, and waits/reaps descendants.
def _slow_poll() -> List[int]:
time.sleep(0.12)
return []
rc_late, _ = run_workload_command(
"true",
timeout_s=0.05,
check_gpu_pids_fn=_slow_poll,
stdout_stream=subprocess.DEVNULL,
)
_check(rc_late == 124, f"late exit past deadline must return 124, got {rc_late}")
rc_bg, _ = run_workload_command(
"sleep 10 &",
timeout_s=0.15,
stdout_stream=subprocess.DEVNULL,
)
_check(rc_bg == 124, f"lingering background descendant must time out with 124, got {rc_bg}")
# 26. select_highest_clean_rung preserves completed rungs in caller-owned history if a later rung raises.
partial_hist: List[SweepOutcome] = []
raised = False
try:
def _fail_second(ndiv: int) -> SweepOutcome:
if ndiv == 70:
return SweepOutcome(
ndiv=70, mhz=945.0, verdict="FAIL_CLOCK_UNAPPLIED", sweeps_completed=0,
mismatched_bytes=0, sec_delta=0, ded_delta=0, peak_gpu_temp_c=45,
peak_mem_temp_c=48, measured_mem_clock_mhz=877.0,
)
raise RuntimeError("boom on rung 67")
select_highest_clean_rung([70, 67], _fail_second, history=partial_hist)
except RuntimeError:
raised = True
_check(raised and len(partial_hist) == 1 and partial_hist[0].ndiv == 70, "partial history lost on probe exception")
# 27. Per-device NDIV map updates only target BDF and preserves other GPUs' overrides.
orig_map = "0000:81:00.0=67,82:00.0=82"
updated_map = update_ndiv_map_entry(orig_map, "00000000:82:00.0", 78)
_check(updated_map == "0000:81:00.0=67,0000:82:00.0=78", f"unexpected map update: {updated_map}")
added_map = update_ndiv_map_entry(orig_map, "0000:b3:00.0", 74)
_check(added_map == "0000:81:00.0=67,0000:82:00.0=82,0000:b3:00.0=74", f"unexpected map add: {added_map}")
removed_map = update_ndiv_map_entry(added_map, "0000:b3:00.0", None)
_check(removed_map == "0000:81:00.0=67,0000:82:00.0=82", f"unexpected map remove: {removed_map}")
# 28. Restore verification fails closed when hardware clock readback does not return to baseline.
with tempfile.TemporaryDirectory() as td:
fake_map = Path(td) / "v100_hbm_ndiv_map"
fake_map.write_text("0000:81:00.0=78\n")
stuck_err = restore_sysfs_ndiv_map(
fake_map,
"0000:81:00.0=65",
no_sysfs=False,
arch="gv100",
expected_baseline_mhz=877.5,
query_telemetry_fn=lambda: EccSample(sec_total=0, ded_total=0, gpu_temp_c=45, mem_clock_mhz=1053.0),
sleep_fn=lambda _s: None,
readback_attempts=2,
readback_delay_s=0.0,
)
_check(stuck_err is not None and "unconfirmed" in stuck_err, f"stuck clock must fail restore: {stuck_err}")
_check(fake_map.read_text().strip() == "0000:81:00.0=65", "map file should still be written back")
ok_err = restore_sysfs_ndiv_map(
fake_map,
"0000:81:00.0=65",
no_sysfs=False,
arch="gv100",
expected_baseline_mhz=877.5,
query_telemetry_fn=lambda: EccSample(sec_total=0, ded_total=0, gpu_temp_c=45, mem_clock_mhz=877.0),
sleep_fn=lambda _s: None,
readback_attempts=2,
readback_delay_s=0.0,
)
_check(ok_err is None, f"confirmed baseline clock restore must succeed, got {ok_err}")
# 29. Isolated CUDA sweep worker enforces timeout and kills hung child process groups.
hung_timed_out = False
try:
run_cuda_sweep_subprocess(
0,
64,
1,
timeout_s=0.15,
telemetry_poll_interval_s=0.05,
worker_cmd_fn=lambda _idx, _out: [sys.executable, "-c", "import time; time.sleep(30)"],
)
except TimeoutError:
hung_timed_out = True
_check(hung_timed_out, "hung CUDA sweep worker must raise TimeoutError")
# 30. Live telemetry polling kills an overheating external workload early (both workload-only and supplemental).
hot_polls = 0
def _overheat_poll() -> Tuple[EccSample, bool]:
nonlocal hot_polls
hot_polls += 1
return EccSample(sec_total=0, ded_total=0, gpu_temp_c=95, mem_temp_c=95, mem_clock_mhz=1053.0), True
live_samples: List[EccSample] = []
t_hot0 = time.monotonic()
rc_hot, _ = run_workload_command(
"sleep 30",
timeout_s=10.0,
live_telemetry_check_fn=_overheat_poll,
telemetry_poll_interval_s=0.05,
telemetry_samples_out=live_samples,
stdout_stream=subprocess.DEVNULL,
)
elapsed_hot = time.monotonic() - t_hot0
_check(
rc_hot == 125 and hot_polls >= 1 and len(live_samples) >= 1 and elapsed_hot < 5.0,
f"overheating workload must abort promptly with rc=125: rc={rc_hot}, polls={hot_polls}, elapsed={elapsed_hot:.2f}s",
)
# Supplemental workload path in run_rung_probe also receives live telemetry polling.
supp_samples = iter(
[
EccSample(sec_total=0, ded_total=0, gpu_temp_c=50, mem_temp_c=55, mem_clock_mhz=1890.0),
EccSample(sec_total=0, ded_total=0, gpu_temp_c=55, mem_temp_c=60, mem_clock_mhz=1890.0),
EccSample(sec_total=0, ded_total=0, gpu_temp_c=56, mem_temp_c=61, mem_clock_mhz=1890.0),
# Mid-workload transient thermal spike (caught live during supplemental workload)
EccSample(sec_total=0, ded_total=0, gpu_temp_c=93, mem_temp_c=94, mem_clock_mhz=1890.0),
# Cooled down by final post-workload sample
EccSample(sec_total=0, ded_total=0, gpu_temp_c=60, mem_temp_c=65, mem_clock_mhz=1890.0),
]
)
def _clean_two_sweeps(
_gpu: int,
_chunk: int,
n_sweeps: int,
cb: Callable[[int], Tuple[EccSample, bool]],
) -> Tuple[int, List[str], List[str], int, List[EccSample], bool]:
mids: List[EccSample] = []
for i in range(n_sweeps):
s, abort = cb(i)
mids.append(s)
if abort:
return 0, ["f16"] * (i + 1), ["f32"] * (i + 1), i + 1, mids, True
return 0, ["f16"] * n_sweeps, ["f32"] * n_sweeps, n_sweeps, mids, False
supp_out = run_rung_probe(
arch="ga100",
gpu=0,
ndiv=70,
sweeps=2,
chunk_mb=64,
max_temp_c=85,
no_sysfs=False,
workload="sleep 30",
write_ndiv_fn=lambda _n: None,
sleep_fn=lambda _s: None,
query_telemetry_fn=lambda: next(supp_samples),
run_sweep_fn=_clean_two_sweeps,
run_workload_fn=lambda cmd, **kw: run_workload_command(
cmd,
timeout_s=5.0,
telemetry_poll_interval_s=0.05,
stdout_stream=subprocess.DEVNULL,
**kw,
),
)
_check(
supp_out.verdict == "FAIL_THERMAL" and supp_out.peak_gpu_temp_c == 93,
f"transient thermal spike during supplemental workload must trigger FAIL_THERMAL: {supp_out}",
)
# 31. Single-sweep GEMM without reference digest cannot pass drift check; CLI enforces --sweeps >= 2 unless --workload-only.
_check(validate_cli_args(parse_args(["--sweeps", "1"])) is not None, "--sweeps 1 must be rejected for GEMM sweeps")
_check(
validate_cli_args(parse_args(["--sweeps", "1", "--workload-only", "--workload", "true"])) is None,
"--sweeps 1 with --workload-only must be allowed",
)
single_unref = evaluate_gate(
arch="gv100",
ndiv=70,
sweeps=1,
max_temp_c=85,
ecc_before=EccSample(sec_total=0, ded_total=0, gpu_temp_c=50, mem_temp_c=55, mem_clock_mhz=945.0),
ecc_after=EccSample(sec_total=0, ded_total=0, gpu_temp_c=55, mem_temp_c=60, mem_clock_mhz=945.0),
byte_mismatches=0,
fp16_digests=["only-one"],
fp32_digests=["only-one"],
clock_verified=True,
)
_check(single_unref.verdict == "FAIL_DIGEST", f"single unreferenced GEMM sweep must FAIL_DIGEST, got {single_unref}")
single_ref_bad = evaluate_gate(
arch="gv100",
ndiv=70,
sweeps=1,
max_temp_c=85,
ecc_before=EccSample(sec_total=0, ded_total=0, gpu_temp_c=50, mem_temp_c=55, mem_clock_mhz=945.0),
ecc_after=EccSample(sec_total=0, ded_total=0, gpu_temp_c=55, mem_temp_c=60, mem_clock_mhz=945.0),
byte_mismatches=0,
fp16_digests=["wrong-fp16"],
fp32_digests=["good-fp32"],
reference_fp16_digest="good-fp16",
reference_fp32_digest="good-fp32",
clock_verified=True,
)
_check(single_ref_bad.verdict == "FAIL_DIGEST", f"mismatched baseline reference digest must FAIL_DIGEST, got {single_ref_bad}")
print(
json.dumps(
{
"self_check": "PASS",
"checks": 43,
"highest_clean_gv100_mock": best,
"sample_outcome": asdict(ok),
},
indent=2,
allow_nan=False,
)
)
return 0
def parse_args(argv: Sequence[str]) -> argparse.Namespace:
p = argparse.ArgumentParser(description="Multi-gen HBM2/HBM2e heat-soak stability gate (#170 / #174)")
p.add_argument("--self-check", action="store_true", help="Run offline unit tests without touching any GPU")
p.add_argument("--arch", choices=("gp100", "gv100", "ga100"), default="gv100")
p.add_argument("--gpu", type=int, default=0, help="CUDA / nvidia-smi GPU index")
p.add_argument("--ndiv", type=int, help="Single NDIV target to qualify")
p.add_argument("--ladder", type=str, help="Comma-separated descending NDIV rungs (e.g. 82,78,74,70,67,65)")
p.add_argument("--sweeps", type=int, default=3, help="Number of heat-soak sweeps per NDIV rung")
p.add_argument("--chunk-mb", type=int, default=256, help="VRAM sweep allocation size in MiB")
p.add_argument("--max-temp-c", type=int, default=85, help="GPU/HBM thermal ceiling in Celsius")
p.add_argument("--workload", type=str, default="", help="Optional shell command to run during soak")
p.add_argument(
"--workload-only",
action="store_true",
help="Run --workload without PyTorch VRAM/GEMM sweeps (retains telemetry, clock, thermal, and ECC checks)",
)
p.add_argument(
"--workload-timeout-s",
type=float,
default=DEFAULT_WORKLOAD_TIMEOUT_S,
help="Per-invocation deadline in seconds for --workload before killing its process group",
)
p.add_argument(
"--sweep-timeout-s",
type=float,
default=DEFAULT_SWEEP_TIMEOUT_S,
help="Per-sweep deadline in seconds for the isolated CUDA sweep worker subprocess",
)
p.add_argument("--json-out", type=Path, help="Optional path to write JSON qualification report")
p.add_argument("--no-sysfs", action="store_true", help="Skip writing sysfs NDIV (qualify current live clock)")
p.add_argument("--_cuda-sweep-worker", action="store_true", help=argparse.SUPPRESS)
p.add_argument("--_worker-out", type=Path, help=argparse.SUPPRESS)
return p.parse_args(argv)
def verify_restored_clock(
arch: str,
expected_baseline_mhz: Optional[float],
query_telemetry_fn: Callable[[], EccSample],
*,
sleep_fn: Callable[[float], None] = time.sleep,
attempts: int = 4,
delay_s: float = 0.25,
) -> Optional[str]:
"""Confirms via live telemetry readback that the hardware memory clock returned to baseline."""
if expected_baseline_mhz is None or not math.isfinite(expected_baseline_mhz):
return "cannot confirm hardware clock restoration: initial baseline memory clock was unavailable"
tol = clock_tolerance_mhz(arch)
last_clk: Optional[float] = None
last_err = ""
for attempt in range(max(1, attempts)):
if attempt > 0:
sleep_fn(delay_s)
sample = query_telemetry_fn()
last_clk = sample.mem_clock_mhz
last_err = sample.error
if (
sample.available
and sample.mem_clock_mhz is not None
and math.isfinite(sample.mem_clock_mhz)
and abs(sample.mem_clock_mhz - expected_baseline_mhz) <= tol
):
return None
if last_clk is None:
detail = last_err or "hardware memory clock readback unavailable"
return (
f"baseline clock restore unconfirmed ({expected_baseline_mhz:.1f} +/- {tol:.1f} MHz): "
f"{detail}"
)
return (
f"baseline clock restore unconfirmed: hardware memory clock readback is {last_clk:.1f} MHz, "
f"expected {expected_baseline_mhz:.1f} +/- {tol:.1f} MHz"
)
def restore_sysfs_ndiv(
param_path: Path,
baseline_ndiv: Optional[int],
*,
no_sysfs: bool,
arch: str = "gv100",
expected_baseline_mhz: Optional[float] = None,
query_telemetry_fn: Optional[Callable[[], EccSample]] = None,
sleep_fn: Callable[[float], None] = time.sleep,
readback_attempts: int = 4,
readback_delay_s: float = 0.25,
) -> Optional[str]:
"""Restores the original NDIV sysfs parameter and optionally verifies live hardware clock
readback; returns an error string on failure."""
if no_sysfs:
return None
if baseline_ndiv is None:
return f"cannot restore {param_path}: initial baseline NDIV was unavailable"
if not param_path.exists():
return (
f"sysfs parameter {param_path} is no longer present while restoring "
f"baseline NDIV {baseline_ndiv}"
)
try:
write_sysfs_ndiv(param_path, baseline_ndiv)
except OSError as exc:
return f"failed to restore baseline NDIV {baseline_ndiv} to {param_path}: {exc}"
if query_telemetry_fn is not None:
sleep_fn(readback_delay_s)
return verify_restored_clock(
arch,
expected_baseline_mhz,
query_telemetry_fn,
sleep_fn=sleep_fn,
attempts=readback_attempts,
delay_s=readback_delay_s,
)
return None
def restore_sysfs_ndiv_map(
map_path: Path,
baseline_map: Optional[str],
*,
no_sysfs: bool,
arch: str = "gv100",
expected_baseline_mhz: Optional[float] = None,
query_telemetry_fn: Optional[Callable[[], EccSample]] = None,
sleep_fn: Callable[[float], None] = time.sleep,
readback_attempts: int = 4,
readback_delay_s: float = 0.25,
) -> Optional[str]:
"""Restores the original per-BDF NDIV map sysfs parameter and verifies hardware clock readback."""
if no_sysfs:
return None
if baseline_map is None:
return f"cannot restore {map_path}: initial baseline NDIV map was unavailable"
if not map_path.exists():
return f"sysfs map parameter {map_path} is no longer present during restore"
try:
write_sysfs_ndiv_map(map_path, baseline_map)
except OSError as exc:
return f"failed to restore baseline NDIV map to {map_path}: {exc}"
if query_telemetry_fn is not None:
sleep_fn(readback_delay_s)
return verify_restored_clock(
arch,
expected_baseline_mhz,
query_telemetry_fn,
sleep_fn=sleep_fn,
attempts=readback_attempts,
delay_s=readback_delay_s,
)
return None
def main(argv: Sequence[str]) -> int:
args = parse_args(argv)
if getattr(args, "_cuda_sweep_worker", False):
if args._worker_out is None:
print("ERROR: --_cuda-sweep-worker requires --_worker-out", file=sys.stderr)
return 2
return _run_cuda_sweep_worker(args.gpu, args.chunk_mb, args._worker_out)
if args.self_check:
return run_self_check()
arg_err = validate_cli_args(args)
if arg_err is not None:
print(f"ERROR: {arg_err}", file=sys.stderr)
return 2
if not run_negative_control():
print("ERROR: negative-control 1-bit flip canary failed!", file=sys.stderr)
return 2
try:
smi_id = resolve_live_nvidia_smi_id(args.gpu)
except ValueError as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 2
rungs: List[int]
if args.ladder is not None:
rungs = parse_ladder_arg(args.ladder)
elif args.ndiv is not None:
rungs = [args.ndiv]
else:
rungs = list(DEFAULT_LADDERS[args.arch])
param_path = SYSFS_PARAM_BY_ARCH[args.arch]
map_path = SYSFS_MAP_PARAM_BY_ARCH.get(args.arch)
use_per_gpu_map = (not args.no_sysfs) and (map_path is not None)
lock_target = map_path if (use_per_gpu_map and map_path is not None) else param_path
target_bdf: Optional[str] = None
if use_per_gpu_map:
target_bdf = query_gpu_pci_bdf_nvidia_smi(smi_id)
if target_bdf is None:
print(
f"ERROR: could not resolve PCI BDF for GPU --id={smi_id} required for per-device "
f"override {map_path}; refusing to modify global {param_path}",
file=sys.stderr,
)
return 2
baseline_ndiv: Optional[int] = None
baseline_map: Optional[str] = None
baseline_mhz: Optional[float] = None
restore_error: Optional[str] = None
probe_error: Optional[str] = None
best: Optional[int] = None
history: List[SweepOutcome] = []
def _on_signal(signum: int, _frame: object) -> None:
raise SystemExit(128 + signum)
signal.signal(signal.SIGINT, _on_signal)
signal.signal(signal.SIGTERM, _on_signal)
def _write_target_ndiv(n: int) -> None:
if use_per_gpu_map and map_path is not None and target_bdf is not None:
current_map = baseline_map if baseline_map is not None else ""
write_sysfs_ndiv_map(map_path, update_ndiv_map_entry(current_map, target_bdf, n))
else:
write_sysfs_ndiv(param_path, n)
def _probe(ndiv: Optional[int]) -> SweepOutcome:
return run_rung_probe(
arch=args.arch,
gpu=args.gpu,
ndiv=ndiv,
sweeps=args.sweeps,
chunk_mb=args.chunk_mb,
max_temp_c=args.max_temp_c,
no_sysfs=args.no_sysfs,
workload=args.workload,
workload_only=args.workload_only,
write_ndiv_fn=_write_target_ndiv,
sleep_fn=time.sleep,
query_telemetry_fn=lambda: query_ecc_and_temp_nvidia_smi(smi_id),
run_sweep_fn=lambda gpu_i, cmb, sw, cb: run_cuda_sweep_subprocess(
gpu_i,
cmb,
sw,
per_sweep_telemetry_fn=cb,
timeout_s=args.sweep_timeout_s,
),
run_workload_fn=lambda cmd, **kw: run_workload_command(
cmd,
timeout_s=args.workload_timeout_s,
smi_id=smi_id,
**kw,
),
)
with sysfs_param_lock(lock_target, no_sysfs=args.no_sysfs):
if not args.no_sysfs:
baseline_sample = query_ecc_and_temp_nvidia_smi(smi_id)
baseline_mhz = baseline_sample.mem_clock_mhz if baseline_sample.available else None
if use_per_gpu_map and map_path is not None:
baseline_map = read_sysfs_ndiv_map(map_path)
if baseline_map is None:
print(
f"ERROR: failed to read baseline NDIV map from {map_path}; "
"pass --no-sysfs to qualify the current live clock without modifying sysfs",
file=sys.stderr,
)
return 2
else:
baseline_ndiv = read_sysfs_ndiv(param_path)
if baseline_ndiv is None:
print(
f"ERROR: failed to read baseline NDIV from {param_path}; "
"pass --no-sysfs to qualify the current live clock without modifying sysfs",
file=sys.stderr,
)
return 2
try:
if args.no_sysfs:
live_outcome = _probe(None)
best = None
history = [live_outcome]
else:
best, _ = select_highest_clean_rung(rungs, _probe, history=history)
except Exception as exc:
probe_error = f"{type(exc).__name__}: {exc}"
print(f"ERROR: probe failed: {probe_error}", file=sys.stderr)
finally:
if use_per_gpu_map and map_path is not None:
restore_error = restore_sysfs_ndiv_map(
map_path,
baseline_map,
no_sysfs=args.no_sysfs,
arch=args.arch,
expected_baseline_mhz=baseline_mhz,
query_telemetry_fn=lambda: query_ecc_and_temp_nvidia_smi(smi_id),
)
else:
restore_error = restore_sysfs_ndiv(
param_path,
baseline_ndiv,
no_sysfs=args.no_sysfs,
arch=args.arch,
expected_baseline_mhz=baseline_mhz,
query_telemetry_fn=lambda: query_ecc_and_temp_nvidia_smi(smi_id),
)
if restore_error is not None:
print(f"ERROR: {restore_error}", file=sys.stderr)
passing_outcome = next((h for h in history if h.verdict == "PASS"), None)
workload_verified_ok = (
not args.workload_only
or (passing_outcome is not None and passing_outcome.workload_gpu_verified is True)
)
recommended = (
None
if (probe_error is not None or restore_error is not None or args.no_sysfs or not workload_verified_ok)
else best
)
live_qualified = bool(
args.no_sysfs
and probe_error is None
and history
and history[0].verdict == "PASS"
and workload_verified_ok
)
report = {
"arch": args.arch,
"gpu": args.gpu,
"nvidia_smi_id": smi_id,
"baseline_ndiv": baseline_ndiv,
"recommended_ndiv": recommended,
"live_clock_qualified": live_qualified if args.no_sysfs else None,
"workload_only": args.workload_only,
"workload_gpu_verified": passing_outcome.workload_gpu_verified if (args.workload_only and passing_outcome is not None) else None,
"probe_error": probe_error,
"restore_ok": restore_error is None,
"restore_error": restore_error,
"history": [asdict(h) for h in history],
}
text = json.dumps(report, indent=2, allow_nan=False)
if args.json_out:
args.json_out.write_text(text + "\n")
print(text)
if probe_error is not None or restore_error is not None:
return 1
if args.no_sysfs:
return 0 if live_qualified else 1
return 0 if recommended is not None else 1
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))