Leszek Bukowski commited on
Commit ·
aaad913
1
Parent(s): 3b640fd
Add pinned shared demo runtime setup helper
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195"""Shared, checksum-pinned setup for the two inference demos. No model training."""from contextlib import contextmanagerimport csvimport hashlibfrom importlib.metadata import distribution, PackageNotFoundErrorimport jsonimport mathimport osfrom pathlib import Pathimport platformimport signalimport shutilimport subprocessimport sysimport threadingimport time
WHEELS = { "probe": { "repo_id": "Lbuk/TheSystem-9B-Probe-256", "revision": "2dd8a6e85fc915a6b8734973ef1348bfd0e66059", }, "lora": { "repo_id": "Lbuk/TheSystem-9B-LoRA", "revision": "196701236ead2e76e38609f919b4cb960c90325d", },}WHEEL_NAME = "thesystem-0.1.0rc1-py3-none-any.whl"WHEEL_SHA256 = "4be1c5ac6d6b9f15c89f06d16b43e734afdb830d3f64b0292bf465b5484119ac"
class RestartRequired(RuntimeError): """Stop Run all before a model can use stale imports."""
@contextmanagerdef visible_progress(label, interval=20): """Immediate status, elapsed-time heartbeats, and an explicit outcome.""" started, stopped = time.monotonic(), threading.Event() print(label, flush=True)
def heartbeat(): while not stopped.wait(interval): print(f" Still running: {label} — {time.monotonic() - started:.0f}s elapsed.", flush=True)
worker = threading.Thread(target=heartbeat, daemon=True) worker.start() try: yield except RestartRequired: print(" Installation saved; a session/kernel restart is required.", flush=True) raise except BaseException as error: print(f" Stopped: {label} — {type(error).__name__}. See the message below.", flush=True) raise else: print(f" Done — {time.monotonic() - started:.1f}s.", flush=True) finally: stopped.set() worker.join()
def check_preflight(): print("Python:", platform.python_version(), flush=True) if sys.version_info[:2] != (3, 12): raise RuntimeError( "Python 3.12 is required. In Colab, select Runtime → Change runtime type → " "Runtime version 2026.07, reconnect, then rerun Prepare runtime. " "For a local kernel, create a Python 3.12 environment. No packages were installed." ) if platform.system() != "Linux" or not shutil.which("nvidia-smi"): raise RuntimeError("Use a Linux NVIDIA GPU runtime. This is not a Mac/CPU demo.") gpu_id = os.environ.get("CUDA_VISIBLE_DEVICES", "0").split(",")[0].strip() if not gpu_id or gpu_id == "-1": raise RuntimeError("CUDA_VISIBLE_DEVICES hides all GPUs. Select a visible NVIDIA GPU.") result = subprocess.run( ["nvidia-smi", f"--id={gpu_id}", "--query-gpu=name,driver_version,memory.total", "--format=csv,noheader,nounits"], check=True, capture_output=True, text=True, timeout=30, ) print("NVIDIA GPU — name, driver, total memory (MiB):", flush=True) print(result.stdout.strip(), flush=True) try: row = next(csv.reader(result.stdout.splitlines(), skipinitialspace=True)) memory_gib = float(row[2]) / 1024 except (StopIteration, IndexError, ValueError) as error: raise RuntimeError("Could not read GPU memory. Inspect nvidia-smi output before installing.") from error if not math.isfinite(memory_gib) or memory_gib < 40: raise RuntimeError( f"At least 40 GiB on one GPU is required; detected {memory_gib:.2f} GiB. " "Select a larger GPU runtime. No packages were installed." ) print("Python and memory passed; native BF16 support will be verified after installation.", flush=True)
def run_command(command, log_path, allowed=(0,)): """Keep detailed output on disk while the enclosing stage shows heartbeats.""" with Path(log_path).open("a", encoding="utf-8") as log: log.write(f"\n{time.strftime('%Y-%m-%d %H:%M:%S')} — {' '.join(command)}\n") log.flush() child = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) try: returncode = child.wait() except BaseException: print("Stopping setup subprocesses…", flush=True) for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGKILL): if child.poll() is not None: break try: os.killpg(child.pid, sig) child.wait(timeout=5) except ProcessLookupError: break except subprocess.TimeoutExpired: continue raise if returncode not in allowed: tail = Path(log_path).read_text(errors="replace")[-6000:] print("Last setup log lines:\n" + tail, flush=True) raise RuntimeError(f"Setup command failed (exit {returncode}). Full log: {log_path}") return returncode
def install_wheel(variant, log_path): from huggingface_hub import hf_hub_download from huggingface_hub.errors import HfHubHTTPError try: wheel = Path(hf_hub_download( **WHEELS[variant], filename=WHEEL_NAME, token=os.environ.get("HF_TOKEN") or False, )) except HfHubHTTPError as error: if error.response is not None and error.response.status_code in (401, 403): raise RuntimeError( "Hugging Face denied access. Rerun Prepare runtime and enter a valid read token " "for the private model repository. Browser login does not authenticate Colab." ) from None raise if hashlib.sha256(wheel.read_bytes()).hexdigest() != WHEEL_SHA256: raise RuntimeError("Wheel checksum mismatch. Stop and obtain a fresh release notebook.") try: previous = json.loads(distribution("thesystem").read_text("direct_url.json") or "{}").get("archive_info", {}) except PackageNotFoundError: 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) 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.")
def verify_live_runtime(): from thesystem._vendor.lora.setup_runtime import verify_runtime verify_runtime() import torch 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) return torch
def prepare_runtime(variant): if variant not in WHEELS: raise ValueError("Choose probe or lora.") 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) try: with visible_progress("[1/5] Check Python and GPU memory"): 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"): install_wheel(variant, log_path) with visible_progress("[4/5] Prepare GPU libraries — first setup may take several minutes"): code = run_command([sys.executable, "-m", "thesystem._vendor.lora.setup_runtime"], log_path, allowed=(0, 10)) if code == 10: raise RestartRequired("GPU libraries were installed or updated.") with visible_progress("[5/5] Verify the active kernel, CUDA and native BF16"): 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." ) 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) return torchprepare_runtime.pyAdded+195