AQIT 0.1.0
Loading...
Searching...
No Matches
vram_guard.py
Go to the documentation of this file.
1# Copyright (c) 2025-present Aquin Labs Private Limited. All Rights Reserved.
2"""VRAM helpers for heavy jobs (simulate) that load their own HF weights."""
3
4from __future__ import annotations
5
6import gc
7from typing import Callable
8
9from aquin.compute.device import (
10 empty_device_cache,
11 is_oom_error,
12 probe_backend,
13 resolve_compute_device,
14)
15
16
17def accelerator_vram_gib() -> tuple[float, float] | None:
18 """Free/total GiB for the active accelerator (CUDA/ROCm only; MPS has no public API)."""
19 import torch
20
21 if torch.cuda.is_available():
22 free_b, total_b = torch.cuda.mem_get_info()
23 return free_b / (1024**3), total_b / (1024**3)
24 return None
25
26
27def cuda_vram_gib() -> tuple[float, float] | None:
28 """Backward-compatible alias."""
30
32def log_accelerator_vram(log: Callable[[str], None] | None = None) -> None:
34 dev = resolve_compute_device()
35 if info is None:
36 if dev == "mps":
37 line = "VRAM: MPS (Metal) — no per-process memory query"
38 else:
39 return
40 else:
41 free_g, total_g = info
42 line = f"VRAM: {free_g:.1f} GiB free / {total_g:.1f} GiB total ({dev})"
43 if log:
44 log(line)
45 else:
46 print(f"[vram] {line}", flush=True)
47
48
49def log_cuda_vram(log: Callable[[str], None] | None = None) -> None:
51
52
54 """Unload HookedTransformer / embedding caches so simulate can own the GPU."""
55 from aquin.compute.model_runtime import unload_weights
56
57 unload_weights(clear_active=False)
58 gc.collect()
59 empty_device_cache()
60
61
62def cleanup_heavy_job_vram() -> None:
63 """Drop any models loaded during a heavy job (simulate TL cache, HF weights)."""
65
67def restore_session_model(model_id: str | None) -> None:
68 if not (model_id or "").strip():
69 return
70 try:
71 from aquin.compute.model_loader import reload_vram_for_model
72
73 reload_vram_for_model(model_id.strip())
74 print(f"[vram] reloaded session model: {model_id}", flush=True)
75 except Exception as exc:
76 print(
77 f"[vram] could not reload session model '{model_id}': {exc}\n"
78 f" Run: aquin load --model {model_id}",
79 flush=True,
80 )
81
82
83def oom_message(*, job: str, model_id: str) -> str:
85 dev = resolve_compute_device()
86 vram_bit = ""
87 if info:
88 free_g, total_g = info
89 vram_bit = f" {dev} has {free_g:.1f} GiB free of {total_g:.1f} GiB."
90 elif dev == "mps":
91 vram_bit = " MPS (Metal) unified memory."
92 return (
93 f"Out of memory during {job} for '{model_id}'.{vram_bit} "
94 "Simulate loads its own copy of the model — use a smaller model "
95 "(e.g. gpt2-small, llama-3.2-1b), free memory from other processes, "
96 "or run: aquin load --model <smaller-id>."
97 )
98
99
100def cuda_oom_message(*, job: str, model_id: str) -> str:
101 return oom_message(job=job, model_id=model_id)
102
103
104def raise_if_cuda_oom(exc: BaseException, *, job: str, model_id: str) -> None:
105 if is_oom_error(exc):
106 raise RuntimeError(oom_message(job=job, model_id=model_id)) from exc
107 raise exc
109
110def backend_summary() -> str:
111 return probe_backend()["summary"]
None restore_session_model(str|None model_id)
Definition vram_guard.py:71
tuple[float, float]|None accelerator_vram_gib()
Definition vram_guard.py:21
None raise_if_cuda_oom(BaseException exc, *, str job, str model_id)
None log_accelerator_vram(Callable[[str], None]|None log=None)
Definition vram_guard.py:36
str cuda_oom_message(*, str job, str model_id)
None log_cuda_vram(Callable[[str], None]|None log=None)
Definition vram_guard.py:53
tuple[float, float]|None cuda_vram_gib()
Definition vram_guard.py:31
str oom_message(*, str job, str model_id)
Definition vram_guard.py:87