Hussein
Claude Opus 5 (1M context)
Resolve tf32 against the GPU, and reject GPUs PyTorch cannot use
85d3028
Raw History Blame Contribute Delete
11.8 kB
"""GPU preflight, checkpoint discovery, and reproducibility metadata."""
from __future__ import annotations
import importlib.metadata
import shutil
from itertools import combinations
from pathlib import Path
from typing import Any
from buddi_asr.data.manifest import read_manifest, resolve_audio_path
from buddi_asr.data.validate import validate_manifest
from buddi_asr.errors import ManifestError, OptionalDependencyError
from buddi_asr.training.config import load_train_config
# TF32 needs Ampere (compute capability 8.0). Turing and Pascal reject it, and
# Transformers raises rather than ignoring the flag:
# --tf32 requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7
# The configs turn it on because it is free speed where it exists, so resolve it
# against the device the same way precision is resolved, instead of failing a
# run over a performance knob.
TF32_MINIMUM_CAPABILITY = (8, 0)
def resolve_tf32(torch: Any, requested: bool) -> bool:
"""Whether TF32 can actually be enabled on the visible devices."""
if not requested or not torch.cuda.is_available():
return False
return all(
torch.cuda.get_device_capability(index) >= TF32_MINIMUM_CAPABILITY
for index in range(torch.cuda.device_count())
)
def unsupported_devices(torch: Any) -> list[str]:
"""Visible GPUs the installed PyTorch has no compiled kernels for.
A GPU older than the build's oldest target is visible to CUDA, reports its
memory, and passes `is_available()` -- then fails at the first kernel launch.
PyTorch 2.10 dropped sm_60, so a Kaggle P100 gets that far and no further.
Reading the arch list turns a mid-run failure into a preflight message.
"""
try:
arch_list = torch.cuda.get_arch_list()
except Exception: # older torch, or a build without the attribute
return []
supported = {
int(name.removeprefix("sm_"))
for name in arch_list
if name.startswith("sm_") and name.removeprefix("sm_").isdigit()
}
if not supported:
return []
unsupported = []
for index in range(torch.cuda.device_count()):
major, minor = torch.cuda.get_device_capability(index)
if major * 10 + minor not in supported:
name = torch.cuda.get_device_properties(index).name
unsupported.append(f"GPU {index} ({name}, sm_{major}{minor})")
return unsupported
def _gib(byte_count: int) -> float:
return round(byte_count / (1024**3), 2)
def find_latest_checkpoint(output_dir: str | Path) -> Path | None:
"""Return the highest complete ``checkpoint-N`` directory."""
root = Path(output_dir).resolve()
candidates: list[tuple[int, Path]] = []
if not root.is_dir():
return None
for path in root.glob("checkpoint-*"):
if not path.is_dir() or not (path / "trainer_state.json").is_file():
continue
try:
step = int(path.name.removeprefix("checkpoint-"))
except ValueError:
continue
candidates.append((step, path))
return max(candidates, default=(0, None), key=lambda item: item[0])[1]
def resolve_resume_checkpoint(
requested: str | None,
output_dir: str | Path,
) -> Path | None:
"""Resolve ``auto``, ``none``, or an explicit Trainer checkpoint."""
if requested is None or requested.casefold() == "none":
return None
if requested.casefold() == "auto":
return find_latest_checkpoint(output_dir)
checkpoint = Path(requested).expanduser().resolve()
if not checkpoint.is_dir() or not (checkpoint / "trainer_state.json").is_file():
raise RuntimeError(
"resume_from_checkpoint must point to a complete Hugging Face Trainer "
f"checkpoint containing trainer_state.json: {checkpoint}"
)
return checkpoint
def validate_training_manifests(
train_manifest: str | Path,
eval_manifest: str | Path,
*,
check_audio: bool,
test_manifest: str | Path | None = None,
) -> dict[str, Any]:
"""Validate manifests and reject speaker or audio leakage across every split."""
paths = {
"train": Path(train_manifest).resolve(),
"validation": Path(eval_manifest).resolve(),
}
if test_manifest is not None:
paths["test"] = Path(test_manifest).resolve()
reports: dict[str, dict[str, Any]] = {}
records_by_split: dict[str, list[Any]] = {}
speakers_by_split: dict[str, set[str]] = {}
audio_by_split: dict[str, set[str]] = {}
errors: list[str] = []
for split_name, path in paths.items():
report = validate_manifest(path, check_audio=check_audio)
records = list(read_manifest(path))
reports[split_name] = report
records_by_split[split_name] = records
speakers_by_split[split_name] = {record.speaker_id for record in records}
audio_by_split[split_name] = {str(resolve_audio_path(record, path)) for record in records}
errors.extend(f"{split_name}: {message}" for message in report["errors"])
if not records:
errors.append(f"{split_name} manifest is empty")
invalid_splits = sorted(
{record.split for record in records if record.split not in {None, split_name}}
)
if invalid_splits:
errors.append(
f"{split_name} manifest contains unexpected split values: {invalid_splits}"
)
for left, right in combinations(paths, 2):
speaker_overlap = speakers_by_split[left] & speakers_by_split[right]
if speaker_overlap:
errors.append(f"{len(speaker_overlap)} speaker IDs occur in both {left} and {right}")
audio_overlap = audio_by_split[left] & audio_by_split[right]
if audio_overlap:
errors.append(f"{len(audio_overlap)} audio files occur in both {left} and {right}")
if errors:
raise ManifestError("GPU preflight rejected the manifests: " + "; ".join(errors))
result = {
"speaker_overlap": 0,
"audio_overlap": 0,
"audio_files_checked": check_audio,
}
for split_name, path in paths.items():
result[split_name] = {
"path": str(path),
"records": len(records_by_split[split_name]),
"speakers": len(speakers_by_split[split_name]),
"warnings": reports[split_name]["warnings"],
}
return result
def collect_runtime_metadata(torch: Any) -> dict[str, Any]:
"""Collect non-secret software and accelerator details for reproducibility."""
packages: dict[str, str] = {}
for name in ("accelerate", "librosa", "numpy", "peft", "torch", "transformers"):
try:
packages[name] = importlib.metadata.version(name)
except importlib.metadata.PackageNotFoundError:
packages[name] = "not-installed"
devices: list[dict[str, Any]] = []
if torch.cuda.is_available():
for index in range(torch.cuda.device_count()):
properties = torch.cuda.get_device_properties(index)
free_bytes, total_bytes = torch.cuda.mem_get_info(index)
with torch.cuda.device(index):
bf16_supported = bool(torch.cuda.is_bf16_supported())
devices.append(
{
"index": index,
"name": properties.name,
"compute_capability": f"{properties.major}.{properties.minor}",
"total_vram_gib": _gib(total_bytes),
"free_vram_gib": _gib(free_bytes),
"bf16_supported": bf16_supported,
}
)
return {
"packages": packages,
"cuda_available": bool(torch.cuda.is_available()),
"cuda_runtime": torch.version.cuda,
"cudnn_version": torch.backends.cudnn.version(),
"device_count": len(devices),
"devices": devices,
}
def run_gpu_preflight(
config_path: str | Path,
*,
overrides: dict[str, Any] | None = None,
check_audio: bool = True,
minimum_free_vram_gib: float = 0.0,
test_manifest: str | Path | None = None,
) -> dict[str, Any]:
"""Fail before paid training if CUDA, data isolation, or disk state is invalid."""
config = load_train_config(config_path, overrides=overrides)
try:
import torch
except ImportError as exc:
raise OptionalDependencyError(
"GPU preflight requires training dependencies: python -m pip install -e '.[train]'"
) from exc
if not torch.cuda.is_available():
raise RuntimeError(
"CUDA is not available to PyTorch. Use an NVIDIA PyTorch image or install the "
"matching CUDA wheel from https://pytorch.org/get-started/locally/."
)
incompatible = unsupported_devices(torch)
if incompatible:
raise RuntimeError(
"This PyTorch build has no kernels for: "
+ ", ".join(incompatible)
+ f". It was compiled for {', '.join(torch.cuda.get_arch_list())}. "
"Select a newer accelerator or install a build that targets this GPU."
)
runtime = collect_runtime_metadata(torch)
if minimum_free_vram_gib < 0:
raise ValueError("minimum_free_vram_gib cannot be negative")
below_minimum = [
device for device in runtime["devices"] if device["free_vram_gib"] < minimum_free_vram_gib
]
if below_minimum:
names = ", ".join(
f"GPU {device['index']} ({device['free_vram_gib']} GiB free)"
for device in below_minimum
)
raise RuntimeError(
f"Insufficient free VRAM for the requested {minimum_free_vram_gib} GiB floor: {names}"
)
if config.bf16 and not all(device["bf16_supported"] for device in runtime["devices"]):
raise RuntimeError("bf16=true, but at least one selected CUDA device lacks BF16 support")
manifests = validate_training_manifests(
config.train_manifest,
config.eval_manifest,
check_audio=check_audio,
test_manifest=test_manifest,
)
output_dir = Path(config.output_dir).resolve()
disk_anchor = output_dir if output_dir.exists() else output_dir.parent
while not disk_anchor.exists() and disk_anchor != disk_anchor.parent:
disk_anchor = disk_anchor.parent
disk_free_gib = _gib(shutil.disk_usage(disk_anchor).free)
warnings = [
warning
for split_name in ("train", "validation", "test")
if split_name in manifests
for warning in manifests[split_name]["warnings"]
]
if disk_free_gib < 10:
warnings.append(
f"Only {disk_free_gib} GiB disk space is free; dataset caches and checkpoints may fill it"
)
checkpoint = resolve_resume_checkpoint(config.resume_from_checkpoint, output_dir)
precision = "bf16" if config.bf16 else "fp16" if config.fp16 else "fp32"
tf32 = resolve_tf32(torch, config.tf32)
if config.tf32 and not tf32:
warnings.append("tf32 requested but the visible GPUs predate Ampere; it will be off")
return {
"ok": True,
"model": config.model_name_or_path,
"method": config.method,
"precision": precision,
"tf32": tf32,
"output_dir": str(output_dir),
"resume_checkpoint": str(checkpoint) if checkpoint else None,
"per_device_train_batch_size": config.per_device_train_batch_size,
"gradient_accumulation_steps": config.gradient_accumulation_steps,
"effective_batch_per_update": (
config.per_device_train_batch_size
* config.gradient_accumulation_steps
* runtime["device_count"]
),
"disk_free_gib": disk_free_gib,
"runtime": runtime,
"manifests": manifests,
"warnings": warnings,
}