Files
voicebox/scripts/package_rocm.py
e766c7cbfb feat(windows): Native AMD ROCm GPU Acceleration (Resolves #531) (#538)
* feat(windows): add native ROCm support for AMD GPUs

Implements native ROCm architecture for Windows.

- Adds backend build pipeline for voicebox-server-rocm.exe

- Detects AMD GPUs dynamically and routes PyTorch allocations

- Adds automatic download and update logic for ROCm dependencies

- Refactors UI in GpuPage.tsx and GpuAcceleration.tsx to add AMD flows

- Fixes 'Switch to CPU' lock on Windows via Tauri backend_override state

- Resolves PyInstaller/rocm_sdk UnboundLocalError silent crashes

- Resolves Numba/NumPy 2.x incompatibilities during Qwen3-TTS load

- Resolves HF_HUB_OFFLINE Catch-22 for CustomVoice processor caching

* fix(rocm): host libs archive under the app release tag, drop offline-load regression

Align the ROCm libs download with the CUDA pattern: both the server core and
the libs archive are published under the app-version release tag, with the libs
content version encoded in the filename only. The previous code fetched libs
from a separate rocm7.2-v1 tag, which disagreed with the download test.

Also revert the unrelated Qwen CustomVoice changes that wrapped model loading in
force_offline_if_cached (not imported — a NameError on load for every platform)
and re-added a Base-model cache gate. The inference-path offline guard was
deliberately removed previously.

* feat(rocm): gate download on AMD detection and persist the backend variant

The ROCm download section now only shows when the backend reports an AMD GPU on
Windows (new supports_rocm health field, backed by the memoized
is_amd_gpu_windows detection that was previously unused), or when ROCm is already
downloaded/active.

Make the backend override honor a pinned variant: set_backend_override persists
the choice to disk so it survives an app restart, start_server reads it back,
and a cuda/rocm pin now actually selects that variant instead of always
preferring ROCm. A stale pin to a deleted backend self-heals to the default
order rather than forcing CPU. Add the web no-op stub for the new method.

* chore(rocm): drop incomplete vitest harness for the unused GpuAcceleration component

GpuAcceleration.tsx is not routed anywhere (GpuPage is the live settings view),
and the added vitest setup referenced testing-library/vitest deps that were not
in the lockfile, breaking the web typecheck. Remove the dead component's test
and its scaffolding to keep this PR scoped to the ROCm feature.

* ci(rocm): add ROCm release-artifact pipeline

Mirror the CUDA packaging path for ROCm so the runtime download has artifacts to
fetch. scripts/package_rocm.py splits the PyInstaller --rocm onedir into
voicebox-server-rocm.tar.gz (core) + rocm-libs-rocm7.2-v1.tar.gz (AMD runtime:
HIP DLLs, rocBLAS Tensile data, MIOpen kernel DBs) + rocm-libs.json, matching
the names services/rocm.py expects, both under the app-version release tag.

The new build-rocm-windows job in release.yml builds on windows-latest/cp312 and
lets build_binary.py --rocm pull the official AMD Radeon wheels.

The file classifier can't be validated against a real AMD build on CI, so it has
unit coverage (test_package_rocm.py) against a synthetic onedir layout. The
prefixes/dir markers may need a tweak after the first real build on AMD
hardware — the packager hard-fails loudly if it classifies zero ROCm files.

---------

Co-authored-by: Jamie Pine <[email protected]>
2026-06-30 15:43:18 -07:00

252 lines
8.5 KiB
Python

"""
Package the PyInstaller --onedir ROCm build into two archives.
Takes the PyInstaller --onedir output directory and splits it into:
1. voicebox-server-rocm.tar.gz — server core (exe + non-AMD deps)
2. rocm-libs-{version}.tar.gz — AMD/ROCm runtime libraries only
3. rocm-libs.json — version manifest for the ROCm libs
Mirrors scripts/package_cuda.py. The split lets the server core re-download on
every app update while the much larger ROCm runtime stays cached until the
toolkit version bumps.
Usage:
python scripts/package_rocm.py backend/dist/voicebox-server-rocm/
python scripts/package_rocm.py backend/dist/voicebox-server-rocm/ --output release-assets/
python scripts/package_rocm.py backend/dist/voicebox-server-rocm/ --rocm-libs-version rocm7.2-v1
"""
import argparse
import hashlib
import json
import sys
import tarfile
from pathlib import Path
# DLL/.so name prefixes that identify AMD ROCm/HIP runtime libraries. They may
# sit in torch/lib/ (torch's bundled HIP runtime) or inside the bundled ROCm SDK
# packages. Matched case-insensitively against the file's base name.
ROCM_DLL_PREFIXES = (
"amdhip",
"amd_comgr",
"amdocl",
"hiprtc",
"hipblaslt",
"hipblas",
"hipfft",
"hiprand",
"hipsolver",
"hipsparse",
"hip",
"rocblas",
"rocfft",
"rocrand",
"rocsolver",
"rocsparse",
"rocprofiler",
"roctracer",
"roctx",
"rocm_smi",
"miopen",
"rccl",
"hsa-runtime",
"hsa",
)
# Directory markers for the bundled ROCm SDK runtime packages. Everything under
# these trees except Python sources (the pure-python rocm_sdk glue) is part of
# the runtime payload — this is where rocBLAS Tensile data and MIOpen kernel
# databases live, which dominate the download size.
ROCM_LIB_DIR_MARKERS = (
"_rocm_sdk_core",
"_rocm_sdk_libraries_custom",
"rocm_sdk_core",
"rocm_sdk_libraries_custom",
)
# Heavy native/data extensions shipped by the ROCm runtime (HIP fat binaries,
# rocBLAS Tensile data, MIOpen kernel DBs).
ROCM_LIB_EXTS = (".dll", ".so", ".dat", ".db", ".kdb", ".hsaco", ".co", ".bc")
# Python sources stay in the server core so the rocm_sdk import glue remains
# alongside the exe. (Both archives extract into backends/rocm/, so this only
# affects which archive carries the file, not runtime resolution.)
_PYTHON_EXTS = (".py", ".pyc", ".pyi")
def is_rocm_file(rel_path: str) -> bool:
"""Check if a relative path belongs to the AMD ROCm runtime libraries.
Identifies large ROCm/HIP runtime DLLs and the SDK runtime payload
(kernel databases, Tensile data) regardless of where PyInstaller placed
them, while keeping pure-python glue in the server core.
"""
rel_lower = rel_path.lower().replace("\\", "/")
name = rel_lower.rsplit("/", 1)[-1]
# Never split out Python sources / stubs.
if name.endswith(_PYTHON_EXTS):
return False
# Native payload inside the bundled ROCm SDK package trees.
if any(marker in rel_lower for marker in ROCM_LIB_DIR_MARKERS):
if name.endswith(ROCM_LIB_EXTS):
return True
# ROCm/HIP DLLs/shared objects anywhere (e.g. _internal/torch/lib/amdhip64.dll).
if name.endswith((".dll", ".so")):
name_no_ext = name.rsplit(".", 1)[0]
for prefix in ROCM_DLL_PREFIXES:
if name_no_ext.startswith(prefix):
return True
return False
def sha256_file(path: Path) -> str:
"""Compute SHA-256 hex digest of a file."""
h = hashlib.sha256()
with open(path, "rb") as f:
while True:
chunk = f.read(1024 * 1024)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
def package(
onedir_path: Path,
output_dir: Path,
rocm_libs_version: str,
torch_compat: str,
):
output_dir.mkdir(parents=True, exist_ok=True)
# Collect all files in the onedir output, split into core vs rocm.
core_files = []
rocm_files = []
for item in sorted(onedir_path.rglob("*")):
if item.is_dir():
continue
rel = item.relative_to(onedir_path)
rel_str = str(rel)
if is_rocm_file(rel_str):
rocm_files.append((rel_str, item))
else:
core_files.append((rel_str, item))
core_size = sum(f.stat().st_size for _, f in core_files)
rocm_size = sum(f.stat().st_size for _, f in rocm_files)
print(f"Input directory: {onedir_path}")
print(f"Core files: {len(core_files)} ({core_size / (1024**2):.1f} MB)")
print(f"ROCm files: {len(rocm_files)} ({rocm_size / (1024**2):.1f} MB)")
if not rocm_files:
print(
f"ERROR: No ROCm files found in {onedir_path}. "
"Refusing to create an empty ROCm libs archive.",
file=sys.stderr,
)
print(
"Make sure you built with --rocm and the ROCm SDK packages are present. "
"If the layout differs, adjust ROCM_DLL_PREFIXES / ROCM_LIB_DIR_MARKERS.",
file=sys.stderr,
)
sys.exit(1)
# Create server core archive. Files are stored relative to the archive root
# (no parent prefix) so extracting to backends/rocm/ lands at the right level.
server_archive = output_dir / "voicebox-server-rocm.tar.gz"
print(f"\nCreating server core archive: {server_archive.name}")
with tarfile.open(server_archive, "w:gz") as tar:
for rel_str, full_path in core_files:
tar.add(full_path, arcname=rel_str)
server_sha = sha256_file(server_archive)
(output_dir / "voicebox-server-rocm.tar.gz.sha256").write_text(
f"{server_sha} voicebox-server-rocm.tar.gz\n"
)
print(f" Size: {server_archive.stat().st_size / (1024**2):.1f} MB")
print(f" SHA-256: {server_sha[:16]}...")
# Create ROCm libs archive.
rocm_libs_archive = output_dir / f"rocm-libs-{rocm_libs_version}.tar.gz"
print(f"\nCreating ROCm libs archive: {rocm_libs_archive.name}")
with tarfile.open(rocm_libs_archive, "w:gz") as tar:
for rel_str, full_path in rocm_files:
tar.add(full_path, arcname=rel_str)
rocm_sha = sha256_file(rocm_libs_archive)
(output_dir / f"rocm-libs-{rocm_libs_version}.tar.gz.sha256").write_text(
f"{rocm_sha} rocm-libs-{rocm_libs_version}.tar.gz\n"
)
print(f" Size: {rocm_libs_archive.stat().st_size / (1024**2):.1f} MB")
print(f" SHA-256: {rocm_sha[:16]}...")
# Write rocm-libs.json manifest.
manifest = {
"version": rocm_libs_version,
"torch_compat": torch_compat,
"archive": rocm_libs_archive.name,
"sha256": rocm_sha,
}
manifest_path = output_dir / "rocm-libs.json"
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")
print(f"\nManifest: {manifest_path.name}")
print(json.dumps(manifest, indent=2))
# Summary
total_input = core_size + rocm_size
total_output = server_archive.stat().st_size + rocm_libs_archive.stat().st_size
print(f"\nTotal input: {total_input / (1024**3):.2f} GB")
print(f"Total output: {total_output / (1024**3):.2f} GB (compressed)")
print(
f"Server core: {server_archive.stat().st_size / (1024**2):.1f} MB (redownloaded on app update)"
)
print(
f"ROCm libs: {rocm_libs_archive.stat().st_size / (1024**2):.1f} MB (cached until ROCm toolkit bump)"
)
def main():
parser = argparse.ArgumentParser(
description="Package PyInstaller --onedir ROCm build into server + ROCm libs archives"
)
parser.add_argument(
"input",
type=Path,
help="Path to PyInstaller --onedir output directory (e.g. backend/dist/voicebox-server-rocm/)",
)
parser.add_argument(
"--output",
type=Path,
default=None,
help="Output directory for archives (default: same as input parent)",
)
parser.add_argument(
"--rocm-libs-version",
type=str,
default="rocm7.2-v1",
help="Version string for the ROCm libs archive (default: rocm7.2-v1)",
)
parser.add_argument(
"--torch-compat",
type=str,
default=">=2.9.0,<2.10.0",
help="Torch version compatibility range (default: >=2.9.0,<2.10.0)",
)
args = parser.parse_args()
if not args.input.is_dir():
print(f"Error: {args.input} is not a directory", file=sys.stderr)
print("Expected a PyInstaller --onedir output directory.", file=sys.stderr)
sys.exit(1)
output_dir = args.output or args.input.parent
package(args.input, output_dir, args.rocm_libs_version, args.torch_compat)
if __name__ == "__main__":
main()