cmvr-visual/inference/scripts/install_dialogue_env.py

137 lines
4.7 KiB
Python
Raw Normal View History

"""Build the dialogue worker environment against the deployed, read-only GPU libraries.
Run with the server's /usr/local/bin/python3.12. Only dialogue-v1 paths are written.
The package and model installers use the same single-transfer lock and speed limit.
"""
import argparse
import fcntl
import hashlib
import json
import os
import subprocess
import sys
from importlib.metadata import distributions
from pathlib import Path
def ensure_package(cache, spec):
requirement, wanted = spec.split(" --hash=sha256:")
name, version = requirement.split("==")
# Pick the exact wheel/sdist already validated by the model acceptance jobs.
for path in cache.iterdir():
filename = path.name.lower().replace("_", "-")
matches = (
filename.startswith(f"{name}-{version}-")
or filename == f"{name}-{version}.tar.gz"
)
if matches and checksum(path) == wanted:
return path
curl = [
"curl",
"-fsSL",
"--retry",
"3",
"--limit-rate",
"3800k",
"--connect-timeout",
"20",
]
meta = json.loads(
subprocess.check_output(curl + [f"https://pypi.org/pypi/{name}/{version}/json"])
)
item = next(row for row in meta["urls"] if row["digests"]["sha256"] == wanted)
path = cache / item["filename"]
temporary = path.with_name(path.name + ".part")
subprocess.run(curl + ["-C", "-", "-o", str(temporary), item["url"]], check=True)
if checksum(temporary) != wanted:
raise ValueError("Package digest mismatch for " + requirement)
temporary.replace(path)
return path
def checksum(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--verify-only",
action="store_true",
help="Check installed versions and CPU imports",
)
args = parser.parse_args()
base = Path("/workspace/envs/vllm")
env = Path("/workspace/envs/dialogue-v1")
work = Path("/workspace/models/dialogue-v1")
shared = base / "lib/python3.12/site-packages"
target = env / "lib/python3.12/site-packages"
python = env / "bin/python"
if sys.version_info[:2] != (3, 12) or not shared.is_dir():
raise RuntimeError("The existing Python 3.12 GPU runtime is required")
cache = work / "packages"
cache.mkdir(parents=True, exist_ok=True)
lock = (work / "fetch.lock").open("a")
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
if not python.exists():
if args.verify_only:
raise RuntimeError("Missing dialogue environment")
subprocess.run(
[base / "bin/python", "-m", "venv", "--without-pip", env], check=True
)
link = target / "base_gpu.pth"
if not link.exists() and not args.verify_only:
link.write_text(str(shared) + "\n")
if link.read_text().strip() != str(shared):
raise RuntimeError("Unexpected base GPU environment")
requirements = Path(__file__).resolve().parents[1] / "requirements-dialogue.txt"
build = {
**os.environ,
"PYTHONPATH": os.pathsep.join(map(str, (target, shared))),
"CUDA_VISIBLE_DEVICES": "",
"OPENBLAS_NUM_THREADS": "2",
"OMP_NUM_THREADS": "2",
}
installed = {
d.name.lower().replace("_", "-"): d.version
for d in distributions(path=[str(target)])
}
for line in requirements.read_text().splitlines():
if line and not line.startswith("#"):
name, version = line.split()[0].split("==")
if installed.get(name) == version:
continue
if args.verify_only or name in installed:
raise RuntimeError(
f"Expected {name}=={version}, found {installed.get(name)}"
)
archive = ensure_package(cache, line.strip())
subprocess.run(
[
sys.executable,
"-m",
"pip",
"install",
"--no-index",
"--no-deps",
"--no-build-isolation",
"--target",
target,
archive,
],
env=build,
check=True,
)
smoke = (
"from voxcpm import VoxCPM; from transformers import WhisperForConditionalGeneration,"
" WhisperProcessor, SegformerImageProcessor; import torch, librosa, onnxruntime, "
"python_speech_features, zhconv; from torchaudio.compliance.kaldi import fbank"
)
subprocess.run([python, "-c", smoke], env=build, check=True)
if __name__ == "__main__":
main()