Leszek Bukowski commited on
Commit ·
f454fc4
1
Parent(s): d03d2d9
Report GPU memory and explain allocation failures in demos
Browse files20 unmodified lines21222324252627282930313233343536373839404112 unmodified lines54555657585927 unmodified lines878889909192939495969798111 unmodified lines21021121221321421521621721821922022122222322422522622710 unmodified lines23823924024124224311 unmodified lines25525625725825920 unmodified linesWHEELS = {"probe": {"repo_id": "Lbuk/TheSystem-9B-Probe-256","revision": "d5cf2028b0cae19fb117ec554b3d1588f0d19e6e",},"lora": {"repo_id": "Lbuk/TheSystem-9B-LoRA","revision": "71a4a6f3639223008c11546989237961ad67abee",},}WHEEL_NAME = "thesystem-0.1.0rc2-py3-none-any.whl"WHEEL_SHA256 = "e70ccd81bc838f816dd52799b96eb62bb3a1dedd227433f9c8c730f164b6985b"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."""12 unmodified linesprint(" Installation saved; a session/kernel restart is required.", flush=True)raiseexcept BaseException as error:print(f" Stopped: {label} — {type(error).__name__}. See the message below.", flush=True)raiseelse:27 unmodified linesmemory_gib = float(row[2]) / 1024except (StopIteration, IndexError, ValueError) as error:raise RuntimeError("Could not read GPU memory. Inspect nvidia-smi output before installing.") from errorif 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,), env=None):111 unmodified linestry:import torchexcept ImportError as error:raise RuntimeError("PyTorch is missing or broken. Connect a fresh latest Colab A100 runtime.") from errorif 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**3if 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 torch10 unmodified lineswith visible_progress("[1/4] Check the existing Colab GPU runtime"):check_preflight()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"):11 unmodified linesexcept BaseException:print("Setup is not ready. Resolve the error above, then rerun Prepare runtime.", flush=True)raiseprint(f"READY — inference runtime prepared in {time.monotonic() - started:.0f}s. Continue to Load {name}.", flush=True)return torch20 unmodified lines2122232425262728293031323334353637383940414243444546474849505112 unmodified lines6465666768697071727374757677787980818227 unmodified lines110111112113114115116117118111 unmodified lines23023123223323423523623723823924024124224324424524624724810 unmodified lines25926026126226326426526611 unmodified lines27827928028128228320 unmodified linesWHEELS = {"probe": {"repo_id": "Lbuk/TheSystem-9B-Probe-256","revision": "9b7ed1d287bc151d1db7e3c51d5d4d933195d976",},"lora": {"repo_id": "Lbuk/TheSystem-9B-LoRA","revision": "d03d2d9475a3e1801403f8cffa7fb3d05b11187e",},}WHEEL_NAME = "thesystem-0.1.0rc3-py3-none-any.whl"WHEEL_SHA256 = 'f315e2cf911edd113bbde3720ef36ba8dd33d2437b2d1e02c4e00ac40cca12c1'class RestartRequired(RuntimeError):"""Stop Run all before a model can use stale imports."""def gpu_memory_status():"""Best-effort feedback, including after an allocation failed."""torch = sys.modules.get("torch")try:free, total = torch.cuda.mem_get_info()return f"GPU memory: {free / 1024**3:.1f} GiB free of {total / 1024**3:.1f} GiB total."except Exception:return "GPU memory information is unavailable."@contextmanagerdef visible_progress(label, interval=20):"""Immediate status, elapsed-time heartbeats, and an explicit outcome."""12 unmodified linesprint(" Installation saved; a session/kernel restart is required.", flush=True)raiseexcept BaseException as error:torch = sys.modules.get("torch")oom_type = getattr(getattr(torch, "cuda", None), "OutOfMemoryError", ())if isinstance(error, oom_type):message = (f"GPU memory ran out during: {label}. {gpu_memory_status()} ""This operation did not complete. If loading failed, restart the session to clear ""partially loaded weights, then load only one model. For a request, try a shorter ""prompt or fewer max_new_tokens; restart first if memory remains occupied. ""If it still does not fit, choose a GPU with more memory. ""No automatic quantization, CPU offload or input truncation was applied.")print(message, flush=True)raise RuntimeError(message) from Noneprint(f" Stopped: {label} — {type(error).__name__}. See the message below.", flush=True)raiseelse:27 unmodified linesmemory_gib = float(row[2]) / 1024except (StopIteration, IndexError, ValueError) as error:raise RuntimeError("Could not read GPU memory. Inspect nvidia-smi output before installing.") from errorif not math.isfinite(memory_gib) or memory_gib <= 0:raise RuntimeError("Could not read a valid GPU memory capacity. Inspect nvidia-smi output.")print("No memory-size cutoff; native BF16 support will be verified next.", flush=True)def run_command(command, log_path, allowed=(0,), env=None):111 unmodified linestry:import torchexcept ImportError as error:raise RuntimeError("PyTorch is missing or broken. Connect a fresh latest Colab NVIDIA GPU runtime.") from errorif 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 NVIDIA GPU runtime and reconnect.")memory_gib = torch.cuda.get_device_properties(0).total_memory / 1024**3if torch.cuda.get_device_capability(0)[0] < 8 or not torch.cuda.is_bf16_supported():raise RuntimeError("This demo requires native BF16 support. Select a compatible NVIDIA GPU; T4 is unsupported.")print(f"Verified GPU: {torch.cuda.get_device_name(0)} ({memory_gib:.1f} GiB), native BF16.", flush=True)print(gpu_memory_status(), flush=True)print(f"Keeping PyTorch {torch.__version__}, CUDA {torch.version.cuda} and NumPy {version('numpy')}.", flush=True)return torch10 unmodified lineswith visible_progress("[1/4] Check the existing Colab GPU runtime"):check_preflight()verify_live_runtime()print("BF16 weights alone use about 18 GB; loading and requests need extra memory. ""You may try a 24 GB GPU, but fit is not yet validated.", flush=True)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"):11 unmodified linesexcept BaseException:print("Setup is not ready. Resolve the error above, then rerun Prepare runtime.", flush=True)raiseprint(f"READY — inference runtime prepared in {time.monotonic() - started:.0f}s. "f"Continue to Load {name}; setup does not guarantee the model fits in memory.", flush=True)return torch
prepare_runtime.py+39-15