Leszek Bukowski commited on
Commit ·
89bf7e3
1
Parent(s): d5cf202
Use existing Colab PyTorch for inference-only setup
Browse files1123416 unmodified lines2122232424252627282829303132313233343587 unmodified lines12312412512612712812913013113213313413513613713813914012612712812913013113213314314414514614714814915015115215315415515615715813413513613713813914014114214314414514616116216316416516616716816917017117217317417517617717817918018118218318418518614714814915015115215315415515615715815916016116216316416516616716819116917017119417217317417519 unmodified lines1951961971981992002012022032212222232042052062072082092282292302102112122132142152162172182192202212222232242252262272283 unmodified lines232233234244235236237246238239248249250240241242243244252253254255256257258245246247248262263264249250251252253254255256257271258259"""Shared, checksum-pinned setup for the two inference demos. No model training.""""""Inference-only Colab setup: reuse PyTorch, install binary Python packages, never build CUDA."""from contextlib import contextmanagerimport csvimport hashlib16 unmodified linesWHEELS = { "probe": { "repo_id": "Lbuk/TheSystem-9B-Probe-256", "revision": "2dd8a6e85fc915a6b8734973ef1348bfd0e66059", "revision": "d5cf2028b0cae19fb117ec554b3d1588f0d19e6e", }, "lora": { "repo_id": "Lbuk/TheSystem-9B-LoRA", "revision": "196701236ead2e76e38609f919b4cb960c90325d", "revision": "71a4a6f3639223008c11546989237961ad67abee", },}WHEEL_NAME = "thesystem-0.1.0rc1-py3-none-any.whl"WHEEL_SHA256 = "4be1c5ac6d6b9f15c89f06d16b43e734afdb830d3f64b0292bf465b5484119ac"WHEEL_NAME = "thesystem-0.1.0rc2-py3-none-any.whl"WHEEL_SHA256 = "e70ccd81bc838f816dd52799b96eb62bb3a1dedd227433f9c8c730f164b6985b"
class RestartRequired(RuntimeError):87 unmodified lines return returncode
def nvcc_release(path): if not path or not Path(path).is_file(): return None result = subprocess.run([str(path), "--version"], capture_output=True, text=True, timeout=30) match = re.search(r"release (\d+\.\d+)", result.stdout) if result.returncode == 0 else None return match.group(1) if match else None
def pip_nvcc(): try: package = distribution("nvidia-cuda-nvcc") except PackageNotFoundError: return None return next((Path(package.locate_file(f)) for f in package.files or [] if str(f).endswith("/bin/nvcc")), None)INFERENCE_REQUIREMENTS = { "transformers": "transformers==5.17.0", "huggingface-hub": "huggingface-hub>=1.31,<2", "accelerate": "accelerate>=1.15,<2", "safetensors": "safetensors>=0.8,<1",}
def prepare_cuda_compiler(log_path): """Match the extension compiler to the pinned CUDA 13.0 PyTorch build.""" configured = Path(os.environ["CUDA_HOME"]) / "bin/nvcc" if os.environ.get("CUDA_HOME") else None candidates = (configured, shutil.which("nvcc"), pip_nvcc()) nvcc = next((Path(path) for path in candidates if nvcc_release(path) == "13.0"), None) if nvcc is None: print("Installing NVIDIA CUDA 13.0 compiler and headers for the GPU extension…", flush=True) run_command([sys.executable, "-m", "pip", "install", "cuda-toolkit[nvcc,cccl]==13.0.3"], log_path) nvcc = pip_nvcc() if nvcc_release(nvcc) != "13.0": raise RuntimeError("CUDA 13.0 compiler setup failed. Inspect the setup log before continuing.") # Set this before starting the extension builder: its CUDA_HOME is read at import time. os.environ["CUDA_HOME"] = str(nvcc.parent.parent) os.environ["PATH"] = str(nvcc.parent) + os.pathsep + os.environ.get("PATH", "") print(f"CUDA compiler verified: 13.0 ({nvcc}). Host driver unchanged.", flush=True) check_cuda_linker(nvcc, log_path)def missing_requirements(): from packaging.requirements import Requirement missing = [] for name, spec in INFERENCE_REQUIREMENTS.items(): try: compatible = version(name) in Requirement(spec).specifier except PackageNotFoundError: compatible = False if not compatible: missing.append(spec) return missing
def check_cuda_linker(nvcc, log_path): """Catch a missing CUDA runtime link before the lengthy extension build.""" root = nvcc.parent.parent runtime = next((p for folder in ("lib64", "lib") for p in (root / folder / "libcudart.so", root / folder / "libcudart.so.13") if p.is_file()), None) if runtime is None: raise RuntimeError(f"CUDA runtime library is missing under {root}; no extension build started.") # NVIDIA's pip wheel provides the versioned library but may omit the linker alias. # Keep our alias outside installed packages and the system CUDA installation. links = Path.cwd() / ".thesystem-runtime" / "cuda-link" links.mkdir(parents=True, exist_ok=True) alias = links / "libcudart.so" if alias.is_symlink(): alias.unlink() elif alias.exists(): raise RuntimeError(f"Unexpected file at {alias}; refusing to replace it.") alias.symlink_to(runtime.resolve()) existing = [p for p in os.environ.get("LIBRARY_PATH", "").split(os.pathsep) if p and p != str(links)] os.environ["LIBRARY_PATH"] = os.pathsep.join([str(links), *existing]) with tempfile.TemporaryDirectory(prefix="thesystem-cuda-check-") as tmp: source = Path(tmp) / "link_check.cu" source.write_text('#include <cuda_runtime_api.h>\nextern "C" int check() { int n; return cudaGetDeviceCount(&n); }\n') run_command([str(nvcc), "--shared", "-Xcompiler", "-fPIC", "--cudart=shared", str(source), f"-L{links}", "-o", str(Path(tmp) / "link_check.so")], log_path) print("CUDA compiler and runtime-library link check passed.", flush=True)def install_inference_dependencies(log_path): missing = missing_requirements() if not missing: print("Inference libraries are already compatible; no installation needed.", flush=True) return print("Installing binary packages: " + ", ".join(missing), flush=True) # The resolver must not replace the working Colab PyTorch or NumPy indirectly. protected = {name: version(name) for name in ("torch", "numpy")} with tempfile.TemporaryDirectory(prefix="thesystem-inference-") as tmp: constraints = Path(tmp) / "constraints.txt" constraints.write_text("".join(f"{name}=={value}\n" for name, value in protected.items())) run_command([sys.executable, "-m", "pip", "install", "--only-binary=:all:", "--upgrade-strategy", "only-if-needed", "--constraint", str(constraints), *missing], log_path) if any(version(name) != value for name, value in protected.items()): raise RuntimeError("The existing PyTorch/NumPy environment changed unexpectedly. Start a fresh runtime.") if missing_requirements(): raise RuntimeError("Inference dependencies are still incompatible. Inspect the setup log.") check_loaded_versions()
def check_loaded_versions(): """Colab may preload NumPy; replacing its files does not refresh those imports.""" for name in ("numpy", "torch", "transformers"): for name in ("numpy", "torch", "transformers", "huggingface_hub", "accelerate", "safetensors", "thesystem"): module = sys.modules.get(name) loaded = getattr(module, "__version__", None) if loaded and str(loaded).split("+")[0] != version(name).split("+")[0]: if loaded and str(loaded).split("+")[0] != version(name.replace("_", "-")).split("+")[0]: raise RestartRequired(f"{name} is still loaded from an earlier installation.")
19 unmodified lines previous = {} previous_sha = previous.get("hashes", {}).get("sha256") or previous.get("hash", "").removeprefix("sha256=") loaded = any(name == "thesystem" or name.startswith("thesystem.") for name in sys.modules) if previous_sha == WHEEL_SHA256: print("Release wheel checksum verified; matching wheel already installed.", flush=True) return if loaded: raise RestartRequired("Restart before replacing the already imported release package.") run_command([sys.executable, "-m", "pip", "install", "--force-reinstall", "--no-deps", str(wheel)], log_path) print("Release wheel checksum verified.", flush=True) if loaded and previous_sha != WHEEL_SHA256: raise RestartRequired("The installed wheel changed while its code was loaded.") print("Release wheel checksum verified and installed.", flush=True)
def verify_live_runtime(): """Check the existing GPU stack without importing any training installer.""" check_loaded_versions() from thesystem._vendor.lora.setup_runtime import verify_runtime verify_runtime() import torch try: import torch except ImportError as error: raise RuntimeError("PyTorch is missing or broken. Connect a fresh latest Colab A100 runtime.") from error if not re.match(r"^2\.14\.\d+(?:[+.]|$)", torch.__version__): raise RuntimeError( f"This demo supports Colab PyTorch 2.14.x; found {torch.__version__}. " "Use the latest Colab runtime. Setup will not replace PyTorch." ) if not torch.cuda.is_available(): raise RuntimeError("PyTorch cannot access CUDA. Select an A100 runtime and reconnect.") memory_gib = torch.cuda.get_device_properties(0).total_memory / 1024**3 if memory_gib < 40 or torch.cuda.get_device_capability(0)[0] < 8 or not torch.cuda.is_bf16_supported(): raise RuntimeError(f"Native BF16 and at least 40 GiB are required; available: {memory_gib:.1f} GiB.") print(f"Verified GPU: {torch.cuda.get_device_name(0)} ({memory_gib:.1f} GiB), native BF16.", flush=True) print(f"Keeping PyTorch {torch.__version__}, CUDA {torch.version.cuda} and NumPy {version('numpy')}.", flush=True) return torch
3 unmodified lines started = time.monotonic() log_path = Path.cwd() / "thesystem-prepare-runtime.log" name = "Probe-256" if variant == "probe" else "LoRA" print(f"Preparing {name} demo. Long steps report every 20 seconds.\nDetailed setup log: {log_path}", flush=True) print(f"Preparing {name} for inference. Long steps report every 20 seconds.\nDetailed setup log: {log_path}", flush=True) print("Uses built-in PyTorch operations; no CUDA compilation or training checks.", flush=True) try: with visible_progress("[1/5] Check Python and GPU memory"): with visible_progress("[1/4] Check the existing Colab GPU runtime"): check_preflight() with visible_progress("[2/5] Prepare the download client"): run_command([sys.executable, "-m", "pip", "install", "huggingface-hub==1.31.0"], log_path) with visible_progress("[3/5] Download, verify and install the release wheel"): verify_live_runtime() with visible_progress("[2/4] Install only missing inference libraries"): install_inference_dependencies(log_path) with visible_progress("[3/4] Download and verify the release wheel"): install_wheel(variant, log_path) with visible_progress("[4/5] Prepare GPU libraries — first setup may take several minutes"): prepare_cuda_compiler(log_path) code = run_command([sys.executable, "-m", "thesystem._vendor.lora.setup_runtime"], log_path, allowed=(0, 10), env={**os.environ, "PIP_VERBOSE": "1"}) if code == 10: raise RestartRequired("GPU libraries were installed or updated.") with visible_progress("[5/5] Verify the active kernel, CUDA and native BF16"): with visible_progress("[4/4] Verify the active runtime"): torch = verify_live_runtime() except RestartRequired: message = ( "RESTART REQUIRED: Installation completed. In Colab choose Runtime → Restart session; " "in VS Code restart the kernel. Then rerun this same Prepare runtime cell. " "Enter your read token again when prompted." "RESTART REQUIRED: An imported library needs a fresh kernel. In Colab choose Runtime → Restart session; " "in VS Code restart the kernel. Then rerun Prepare runtime and enter your read token again. " "Installed packages stay in place." ) print(message, flush=True) raise RestartRequired(message) from None except BaseException: print("Setup is not ready. Resolve the error above, then rerun Prepare runtime.", flush=True) raise print(f"READY — runtime prepared in {time.monotonic() - started:.0f}s. Continue to Load {name}.", flush=True) print(f"READY — inference runtime prepared in {time.monotonic() - started:.0f}s. Continue to Load {name}.", flush=True) return torchprepare_runtime.py+73-86