fix(setup): the Inkling planner works from the memory that is free, keeps a margin and a screen reserve, and writes GiB (#6662 #6644 #6792 #6739)

- The card: setup already hands the planner min(total, free) of nvidia-smi (effective_vram_gb); a layer split over several cards now sums
  the FREE memory too, not the sizes.
- RAM: new setup.ram_free_gb() (Windows available physical memory; Linux MemAvailable, in a container the cgroup limit minus its use; macOS
  free + inactive pages). The planner (strata_control/inkling_fit.py: ram_free_gib) keeps the experts held in RAM inside the free RAM minus
  1.5 GB; what does not fit streams from disk and is said so, instead of overcommitting.
- A card that drives a display keeps a larger reserve (desktop=True, 0.8 GB, from gpu_drives_display), so the 8 GiB card of #6739 no longer
  ends with 159 MiB free; the margin VRAM_SAFETY_GB (0.3 GB) is explicit and VRAM_DRIVER_GB is recalibrated to what the engine's memory ledger
  measures (1.30 instead of 1.60 with the margin inside), so a headless card gets the plans that were measured to start (0.4-0.5 GiB left).
- The flags: the planner counts GB, strata-inkling reads --vram-experts-gb / --ram-experts-gb as GiB; setup wrote the GB number, so the
  engine's cap sat 7.4% above the plan. inkling_expert_flags() converts.
- Default choice (preference "balanced"): the best build whose experts all sit in the card (the K/V may be in RAM), else SQ-10; the older
  "quality" choice (a bigger build with part of its experts in RAM) stays available. Measured on an RTX 3060 12 GB, drafter off: SQ-10 all in
  the card 34-38 tok/s; SQ-10 with 2.6 GB in RAM 10 tok/s; SQ-15 with 4.7 GB in RAM 4-8 tok/s. With the backend named "cuda" the planner puts
  SQ-15 fully in a 16 GiB card with the K/V in RAM (the engine does it itself there; A4000 16 GB started with 0.4 GiB left); an unnamed
  backend or HIP keeps the older, more cautious rule (#6613).

Tests: test_inkling_fit_free.py (margin, screen reserve, free-RAM cap, unknown free RAM, GiB flags, ram_free_gb on Linux and in a container,
the plan inputs); test_inkling_fit.py follows the new default.
This commit is contained in:
Niko1221 committed 2026-11-23 13:05:15 +01:00
1 parent a8371d27fa
commit 7a1467e217
4 files changed
+253 -31

No files matched your search

+77 -9
View File
@@ -1360,6 +1360,48 @@ def ram_gb():
return total
def ram_free_gb():
"""RAM the PC can give a program right now, in GiB (Windows: GlobalMemoryStatusEx available physical; Linux: MemAvailable, and
in a container the limit minus what the cgroup uses; macOS: free + inactive pages); None when it cannot be read. The Inkling planner
keeps the experts held in RAM inside this (#6662)."""
try:
if WIN:
return _memory_status().ullAvailPhys / 2**30
if sys.platform == "darwin":
text = subprocess.run(["vm_stat"], capture_output=True, text=True, errors="replace", timeout=3, check=True).stdout
page = 4096
m = re.search(r"page size of (\d+) bytes", text)
if m:
page = int(m.group(1))
pages = 0
for line in text.splitlines():
if line.startswith(("Pages free", "Pages inactive", "Pages speculative")):
pages += int(re.sub(r"[^0-9]", "", line.split(":")[1]) or 0)
return pages * page / 2**30
with open("/proc/meminfo") as stream:
for line in stream:
if line.startswith("MemAvailable"):
free = int(line.split()[1]) * 1024 / 2**30
break
else:
return None
limit = _cgroup_memory_limit()
if limit is not None:
used = None
for name in ("/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory/memory.usage_in_bytes"):
try:
with open(name) as stream:
used = int(stream.read().strip())
break
except (OSError, ValueError):
continue
if used is not None:
free = min(free, max(0.0, (limit - used) / 2**30))
return free
except (OSError, ValueError, subprocess.SubprocessError):
return None
def _cgroup_memory_limit(self_cgroup="/proc/self/cgroup", root="/sys/fs/cgroup"):
"""The smallest memory limit (bytes) on this process's cgroup and its ancestors, as the engine's memory guard reads
it (strata_control/cgroup_memory.py). None when no level sets a limit or the files cannot be read."""
@@ -10416,8 +10458,32 @@ def inkling_pc(gpu, ram) -> tuple:
return effective_vram_gb(g), float(ram), False, False, arch
def inkling_menu_lines(vram_gib, ram_gib, unified, ctx=None, vision=inkling_family.DEFAULT_VISION, *, igpu=False, arch=None) -> list:
rec = inkling_fit.recommend(vram_gib, ram_gib, unified, ctx, vision, igpu=igpu, arch=arch)["build"]
def inkling_expert_flags(placed) -> list:
"""--vram-experts-gb / --ram-experts-gb for a planner placement. The planner counts GB (10^9 bytes); strata-inkling reads the two
flags as GiB (2^30 bytes): written as they were, the engine's cap sat 7.4% above the plan (#6792)."""
return ["--vram-experts-gb", f"{placed['vram_gb'] / inkling_fit.GIB_TO_GB:.2f}",
"--ram-experts-gb", f"{placed['ram_gb'] / inkling_fit.GIB_TO_GB:.2f}"]
def inkling_plan_extra(gpu) -> dict:
"""What the Inkling planner is told beside the card's free memory (#6662 #6739): the free RAM, and that the card drives a display
(the desktop keeps a larger reserve). Missing keys mean not known."""
out = {}
free = ram_free_gb()
if free is not None:
out["ram_free_gib"] = free
g = gpu or {}
try:
if g.get("index") is not None and not g.get("uma") and not g.get("unified") and gpu_drives_display(g):
out["desktop"] = True
except Exception: # noqa: BLE001
pass
return out
def inkling_menu_lines(vram_gib, ram_gib, unified, ctx=None, vision=inkling_family.DEFAULT_VISION, *, igpu=False, arch=None, extra=None) -> list:
extra = extra or {}
rec = inkling_fit.recommend(vram_gib, ram_gib, unified, ctx, vision, igpu=igpu, arch=arch, **extra)["build"]
words = {
"full_vram": "100% GPU/UMA resident",
"ram_vram_zero_ssd": "fits in VRAM + RAM (zero SSD spill)",
@@ -10425,7 +10491,7 @@ def inkling_menu_lines(vram_gib, ram_gib, unified, ctx=None, vision=inkling_fami
"cross_tier_ssd": "streams experts from SSD: slower",
}
out = []
for r in inkling_fit.rows(vram_gib, ram_gib, unified, ctx, vision):
for r in inkling_fit.rows(vram_gib, ram_gib, unified, ctx, vision, **extra):
out.append((r["build"], f"{r['build']:7s} {inkling_family.BUILD_ABOUT[r['build']]}; download {r['download_gb']:.1f} GB <- {words[r['mode']]}"
+ (" (recommended)" if r["build"] == rec else "")))
return out
@@ -10566,13 +10632,15 @@ def install_inkling2(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
mgpu_flags = inkling_fit.multi_gpu_flags(ink_gpus, windows=WIN) if (is_cuda_ink and len(ink_gpus) >= 2) else (["--gpus", "2"] if len(ink_gpus) >= 2 else [])
use_ink_ls = "--layer-split" in mgpu_flags
if len(ink_gpus) >= 2:
vram_gib = sum(float(g.get("vram_gb") or 0.0) for g in ink_gpus)
vram_gib = sum(effective_vram_gb(g) for g in ink_gpus)
mode_desc = "pipeline layer-split" if use_ink_ls else "dual-GPU expert parallelism"
ok("GPUs: " + " + ".join(gpu_name(c) for c in ink_gpus) + f" ({mode_desc})")
vision = a.vision not in ("no", "none")
want_ctx = a.context or inkling_family.DEFAULT_CONTEXT
lines = inkling_menu_lines(vram_gib, ram_gib, unified, want_ctx, vision, igpu=igpu, arch=arch)
rec = inkling_fit.recommend(vram_gib, ram_gib, unified, want_ctx, vision, igpu=igpu, arch=arch)
plan_extra = inkling_plan_extra(gpu) if not unified else {}
plan_extra["backend"] = "hip" if hip else ("sycl" if getattr(a, "backend", None) == "sycl" else ("metal" if sys.platform == "darwin" else "cuda"))
lines = inkling_menu_lines(vram_gib, ram_gib, unified, want_ctx, vision, igpu=igpu, arch=arch, extra=plan_extra)
rec = inkling_fit.recommend(vram_gib, ram_gib, unified, want_ctx, vision, igpu=igpu, arch=arch, **plan_extra)
say()
order = [b for b, _ in lines]
for i, (b, text) in enumerate(lines, 1):
@@ -10588,7 +10656,7 @@ def install_inkling2(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
for i, c in enumerate(ctxs, 1):
say(f" {i}) {c // 1024}K tokens" + (" (recommended)" if c == inkling_family.DEFAULT_CONTEXT else ""))
ctx = ctxs[int(ask("Context?", [str(i) for i in range(1, len(ctxs) + 1)], str(ctxs.index(inkling_family.DEFAULT_CONTEXT) + 1), a.yes)) - 1]
placed = inkling_fit.place(model, vram_gib, ram_gib, unified, ctx, vision)
placed = inkling_fit.place(model, vram_gib, ram_gib, unified, ctx, vision, **plan_extra)
mode = inkling_fit.mode(placed)
if mode == "cross_tier_ssd":
warn(f"{model} exceeds this PC's memory: about {placed['ssd_gb']:.1f} GB stream from SSD ({rec['build']} fits better)")
@@ -10669,7 +10737,7 @@ def install_inkling2(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
step(7, "writing the start script")
drafting_mode = "off" if (not want_dspark or (is_gguf and dspark_path is None)) else inkling_family.DEFAULT_DRAFTER
ink_backend = "hip" if hip else ("metal" if sys.platform == "darwin" else ("sycl" if getattr(a, "backend", None) == "sycl" else "cuda"))
placed = inkling_fit.place(model, vram_gib, ram_gib, unified, ctx, bool(vision and vision_path is not None), dspark=(drafting_mode != "off"), backend=ink_backend)
placed = inkling_fit.place(model, vram_gib, ram_gib, unified, ctx, bool(vision and vision_path is not None), dspark=(drafting_mode != "off"), **{**plan_extra, "backend": ink_backend})
args = ["--native", str(model_file), "--max-context", str(ctx)]
kv_asked = str(getattr(a, "kv", None) or "").strip().lower()
if kv_asked in ("fp16", "fp8", "k8v8", "k8v4"):
@@ -10686,7 +10754,7 @@ def install_inkling2(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
if mgpu_flags:
args += mgpu_flags
if not unified and len(ink_gpus) < 2:
args += ["--vram-experts-gb", f"{placed['vram_gb']:.2f}", "--ram-experts-gb", f"{placed['ram_gb']:.2f}"]
args += inkling_expert_flags(placed)
if placed.get("ssd_gb", 0.0) > 0.05:
args += ["--ssd-experts"]
cfg = {
+53 -20
View File
@@ -20,13 +20,19 @@ Multi-request parallelism (`--parallel 1|4|8|32|64`):
from __future__ import annotations
GIB_TO_GB = 1.073741824
VRAM_DRIVER_GB = 1.60 # driver / WDDM / HIP / desktop compositor + runtime & O(1) prefill scratch (#6613)
VRAM_DRIVER_GB = 1.30 # CUDA context + runtime + the engine's working buffers beside the weights, measured: 1.54 GB of non-expert use on a 12 GiB card (was 1.60 with the margin inside; the margin is now VRAM_SAFETY_GB)
VRAM_HYBRID_WORKSPACE_GB = 0.85 # hybrid ping-pong DMA ring + staging buffers + desktop margin (#6587, #6613)
KV_GROW_FACTOR = 1.60 # peak transient headroom for elastic/doubling KV pool growth (HIP grow_pool #6613)
SPLIT_GPU_OVERHEAD_GB = 1.00 # per-extra-GPU runtime/trunk/comm overhead on multi-GPU layer-split
DSPARK_BASE_GB = 0.11 # DSpark activation + compact SWA-1025 rings for layers 0 & 2
DSPARK_KV_BYTES_PER_TOK = 4096 # 1 global DSpark layer (L1) x 8 kv_heads x 128 head_dim x 2 (K+V) x 2B (FP16)
OS_RESERVE_GB = 4.50 # system RAM reserve on discrete or UMA hosts
# #6644 #6792 #6739 #6662: the plan is made from the memory that is FREE now, and keeps a margin on top of what the engine measures.
# Measured (RTX 3060 12 GB, A4000 16 GB, 4090 24 GB; strata-inkling memory ledger): after the experts, the K/V, the workspaces and the
# drafter are in, 0.4-0.5 GiB of the card was left; the margin makes that about 0.7-0.8 GiB, and a card that drives a screen keeps more.
VRAM_SAFETY_GB = 0.30 # taken off the card's free memory before anything is placed
DESKTOP_RESERVE_GB = 0.80 # more, when the card drives a display: the desktop (browser, video) grows after the plan is made
FREE_RAM_MARGIN_GB = 1.50 # free RAM that stays free beside the experts held in RAM
UMA_RESERVE_GB = 5.00 # unified memory OS + driver reserve
SSD_NEAR_RESIDENT_GB = 2.0
VISION_GB = 0.637 # Inkling-2-Mini-Vision.strata (636,526,592 B, CPU / on-demand on <=12 GiB GPUs)
@@ -175,19 +181,24 @@ def non_expert_gb(ctx: int | None = None, parallel: int = 1, vision: bool = Fals
def compute(build: str, vram_gib: float, ram_gib: float, ctx: int | None = None, vision: bool = False,
parallel: int = 1, dspark: bool = True, kv_offload: str = "auto", *,
extra_vram_gib: float = 0.0, backend: str | None = None) -> dict:
extra_vram_gib: float = 0.0, backend: str | None = None,
desktop: bool = False, ram_free_gib: float | None = None) -> dict:
"""Placement of `build` on a discrete-GPU PC (vram_gib + optional extra_vram_gib + ram_gib): GB of experts in VRAM, in RAM, and on SSD.
Implements the unified 4-tier adaptive contract (GPU -> RAM+CPU -> SSD) with Host KV Offloading (#552),
CPU/on-demand Vision on <= 12.5 GiB GPUs, O(1) prefill & KV growth headroom (#6613), and WDDM floor so
4/6/8/10/12/16/24/32+ GB GPUs never OOM even at 32K–128K context with DSpark and Vision enabled.
vram_gib is the card's FREE memory (what is left after the desktop and other programs), ram_free_gib the free RAM
(None: not known, the total in ram_gib counts); desktop says the card drives a display (a larger reserve) (#6662 #6739).
"""
info = BUILDS[build]
v_primary = float(vram_gib or 0.0)
v_extra = max(0.0, float(extra_vram_gib or 0.0))
v_gib = v_primary + v_extra
split_overhead = SPLIT_GPU_OVERHEAD_GB if v_extra > 0.0 else 0.0
vram_gb = max(0.0, v_gib * GIB_TO_GB - split_overhead)
vram_gb = max(0.0, v_gib * GIB_TO_GB - split_overhead - (VRAM_SAFETY_GB if v_gib > 0.0 else 0.0)
- (DESKTOP_RESERVE_GB if (desktop and v_gib > 0.0) else 0.0))
ram_gb = float(ram_gib or 0.0) * GIB_TO_GB
offload_mode = str(kv_offload or "auto").lower()
backend_low = str(backend or "").strip().lower()
@@ -203,6 +214,9 @@ def compute(build: str, vram_gib: float, ram_gib: float, ctx: int | None = None,
vision_in_vram = bool(vision and v_gib > 12.5)
glob_kv = global_kv_gb(ctx, parallel, fp8_kv=fp8_kv)
ram_avail_for_model = max(0.0, ram_gb - OS_RESERVE_GB - (VISION_GB if vision else 0.0))
if ram_free_gib is not None: # the free RAM, not the installed RAM: what other programs hold is not there to give
ram_avail_for_model = max(0.0, min(ram_avail_for_model,
float(ram_free_gib) * GIB_TO_GB - FREE_RAM_MARGIN_GB - (VISION_GB if vision else 0.0)))
# 1. Try 100%-VRAM expert residency with VRAM-resident global KV first
full_need = dense_total + info["bodies_gb"] + non_expert_gb(
@@ -222,7 +236,9 @@ def compute(build: str, vram_gib: float, ram_gib: float, ctx: int | None = None,
# 2. Try 100%-VRAM expert residency with Host KV Offloading (matches CUDA engine auto-offload on <= 13 GiB,
# e.g. 12 GiB RTX 5070 + SQ-10 + lossless FP16 32K; 16 GiB cards keep global KV in VRAM so HIP never OOMs #6613).
can_offload_kv = supports_host_kv and (effective_offload != "off") and (ram_avail_for_model >= glob_kv)
auto_offload_full = can_offload_kv and (effective_offload == "on" or v_gib <= 13.0)
# CUDA (named by the caller) at any card size: the experts all in the card with the K/V in RAM beats experts in RAM
# (measured: SQ-15 on an A4000 16 GB, RESULTS-0221-INKCUDA.md); an unnamed backend keeps the older rule (<= 13 GiB or asked)
auto_offload_full = can_offload_kv and (effective_offload == "on" or v_gib <= 13.0 or backend_low == "cuda")
full_need_offload = dense_total + info["bodies_gb"] + non_expert_gb(
ctx, parallel, vision=vision_in_vram, dspark=dspark, fp8_kv=fp8_kv, hybrid=False, host_offload_global_kv=True
)
@@ -288,11 +304,12 @@ def compute_unified(build: str, pool_gib: float, ctx: int | None = None, vision:
def place(build: str, vram_gib: float | None, ram_gib: float, unified: bool = False, ctx: int | None = None,
vision: bool = False, parallel: int = 1, dspark: bool = True, *,
extra_vram_gib: float = 0.0, backend: str | None = None) -> dict:
extra_vram_gib: float = 0.0, backend: str | None = None,
desktop: bool = False, ram_free_gib: float | None = None) -> dict:
if unified:
return compute_unified(build, ram_gib, ctx, vision, parallel, dspark)
return compute(build, vram_gib or 0.0, ram_gib, ctx, vision, parallel, dspark,
extra_vram_gib=extra_vram_gib, backend=backend)
extra_vram_gib=extra_vram_gib, backend=backend, desktop=desktop, ram_free_gib=ram_free_gib)
def mode(placed: dict | float) -> str:
@@ -313,14 +330,16 @@ def mode(placed: dict | float) -> str:
def fits(build: str, vram_gib: float | None, ram_gib: float, unified: bool = False, ctx: int | None = None,
vision: bool = False, parallel: int = 1, *, extra_vram_gib: float = 0.0, backend: str | None = None) -> bool:
return place(build, vram_gib, ram_gib, unified, ctx, vision, parallel,
extra_vram_gib=extra_vram_gib, backend=backend)["ssd_gb"] <= 0.05
vision: bool = False, parallel: int = 1, *, extra_vram_gib: float = 0.0, backend: str | None = None,
desktop: bool = False, ram_free_gib: float | None = None) -> bool:
return place(build, vram_gib, ram_gib, unified, ctx, vision, parallel, extra_vram_gib=extra_vram_gib, backend=backend,
desktop=desktop, ram_free_gib=ram_free_gib)["ssd_gb"] <= 0.05
def recommend(vram_gib: float | None, ram_gib: float, unified: bool = False, ctx: int | None = None,
vision: bool = False, *, preference: str = "quality", igpu: bool = False, arch: str | None = None,
parallel: int = 1, extra_vram_gib: float = 0.0, backend: str | None = None) -> dict:
vision: bool = False, *, preference: str = "balanced", igpu: bool = False, arch: str | None = None,
parallel: int = 1, extra_vram_gib: float = 0.0, backend: str | None = None,
desktop: bool = False, ram_free_gib: float | None = None) -> dict:
"""Automatic hardware auto-selection for Inkling-2-Mini (docs/10-GUI-TUI.md + Track 1E):
- Radeon 780M (gfx1103) / Strix Point (gfx1150) iGPUs -> SQ-10 (coherent UMA/GTT, zero BIOS carve-out OOM)
- >= 24 GiB discrete GPU (or combined multi-GPU VRAM) OR >= 32 GiB UMA -> SQ-20
@@ -345,16 +364,29 @@ def recommend(vram_gib: float | None, ram_gib: float, unified: bool = False, ctx
best = "SQ-10"
else:
use_unified = False
if v >= 22.0:
best = "SQ-20"
elif v >= 15.0:
best = "SQ-10" if (str(preference).lower() == "speed" or r < 20.0) else "SQ-15"
elif v >= 11.0:
best = "SQ-10" if (str(preference).lower() == "speed" or r < 24.0) else "SQ-15"
pref = str(preference).lower()
if pref == "quality":
# the biggest build that fits with part of its experts in RAM (slower: measured 4-8 tok/s for SQ-15 on a 12 GiB card)
if v >= 22.0:
best = "SQ-20"
elif v >= 15.0:
best = "SQ-10" if r < 20.0 else "SQ-15"
elif v >= 11.0:
best = "SQ-10" if r < 24.0 else "SQ-15"
else:
best = "SQ-10"
else:
# balanced (the default; "speed" is the same): the best build whose experts all sit in the card (the K/V may be in RAM),
# else SQ-10. Experts moved to RAM cost most of the speed (SQ-10 on a 3060: about 35 tok/s resident, 10 tok/s with 2.6 GB in RAM).
best = "SQ-10"
for cand in STRATA_ORDER:
pc = place(cand, vram_gib, ram_gib, False, ctx, vision, parallel, extra_vram_gib=extra_vram_gib, backend=backend,
desktop=desktop, ram_free_gib=ram_free_gib)
if pc.get("full_vram") and pc["ssd_gb"] <= 0.05:
best = cand
break
placed = place(best, vram_gib, ram_gib, use_unified, ctx, vision, parallel,
extra_vram_gib=extra_vram_gib, backend=backend)
extra_vram_gib=extra_vram_gib, backend=backend, desktop=desktop, ram_free_gib=ram_free_gib)
return {
"build": best,
"placement": placed,
@@ -365,10 +397,11 @@ def recommend(vram_gib: float | None, ram_gib: float, unified: bool = False, ctx
def rows(vram_gib: float | None, ram_gib: float, unified: bool = False, ctx: int | None = None,
vision: bool = False, parallel: int = 1) -> list[dict]:
vision: bool = False, parallel: int = 1, *, desktop: bool = False, ram_free_gib: float | None = None,
backend: str | None = None) -> list[dict]:
out = []
for b in ORDER:
placed = place(b, vram_gib, ram_gib, unified, ctx, vision, parallel)
placed = place(b, vram_gib, ram_gib, unified, ctx, vision, parallel, desktop=desktop, ram_free_gib=ram_free_gib, backend=backend)
dl = BUILDS[b]["file_gb"] + (DSPARK_GGUF_GB if is_gguf_build(b) else 0.0)
out.append({
"build": b,
+19 -2
View File
@@ -36,11 +36,21 @@ class TestInklingFitAndHardwareSelection(unittest.TestCase):
def test_discrete_16gb_and_24gb_mac_select_sq15(self):
# #6613: 16 GiB discrete GPU at 32K plans SQ-15 as safe hybrid (never OOMing on KV growth),
# while speed preference selects 100%-VRAM SQ-10 and 24 GiB Mac UMA fits SQ-15 100% in memory.
rec_16 = inkling_fit.recommend(vram_gib=16, ram_gib=32)
# quality: the biggest build with part of its experts in RAM (safe on HIP, slow); CUDA balanced: SQ-15 all in the card, K/V in RAM
rec_16 = inkling_fit.recommend(vram_gib=16, ram_gib=32, preference="quality")
self.assertEqual(rec_16["build"], "SQ-15")
self.assertEqual(rec_16["mode"], "ram_vram_zero_ssd")
self.assertTrue(rec_16["fits"])
self.assertLessEqual(rec_16["placement"]["vram_gb"], 10.6)
rec_16_cuda = inkling_fit.recommend(vram_gib=16, ram_gib=32, backend="cuda")
self.assertEqual(rec_16_cuda["build"], "SQ-15")
self.assertEqual(rec_16_cuda["mode"], "full_vram")
self.assertGreater(rec_16_cuda["placement"]["host_kv_gb"], 0.5)
# a backend that is not named, or HIP, keeps SQ-10 (the K/V grow pool of #6613 has no room beside SQ-15)
for bkd in (None, "hip"):
rec_16_safe = inkling_fit.recommend(vram_gib=16, ram_gib=32, backend=bkd)
self.assertEqual(rec_16_safe["build"], "SQ-10", bkd)
self.assertEqual(rec_16_safe["mode"], "full_vram", bkd)
rec_16_speed = inkling_fit.recommend(vram_gib=16, ram_gib=32, preference="speed")
self.assertEqual(rec_16_speed["build"], "SQ-10")
@@ -115,7 +125,7 @@ class TestInklingFitAndHardwareSelection(unittest.TestCase):
# #6613: 16 GiB (and 15.92 GiB Radeon RX 9060 XT / RX 9070 XT) + SQ-15 + 32K must NOT plan full_vram=True
# (12.28 GB experts leaves <100 MiB for HIP kv grow_pool); it keeps safe VRAM headroom (~10.44-10.53 GB experts)
# while SQ-10 fits 100% in VRAM at 32K and SQ-15 fits 100% in VRAM at 8K.
for v_16, bkd in ((15.92, "hip"), (15.92, None), (16.0, "cuda")):
for v_16, bkd in ((15.92, "hip"), (15.92, None)):
p16 = inkling_fit.compute("SQ-15", v_16, 64, 32768, backend=bkd)
self.assertEqual(p16["kv_dtype"], "fp16")
self.assertFalse(p16["full_vram"], (v_16, bkd, p16))
@@ -124,6 +134,13 @@ class TestInklingFitAndHardwareSelection(unittest.TestCase):
self.assertEqual(p16["ssd_gb"], 0.0)
self.assertEqual(p16["host_kv_gb"], 0.0)
# CUDA names itself: all 12.28 GB of SQ-15 experts in the card, the K/V in RAM (the engine does this by itself on a card this size;
# an A4000 16 GB kept 0.4 GiB free after start-up and answered 8K prompts: RESULTS-0221-INKCUDA.md)
p16_cuda = inkling_fit.compute("SQ-15", 15.5, 64, 32768, backend="cuda")
self.assertTrue(p16_cuda["full_vram"], p16_cuda)
self.assertEqual(p16_cuda["ram_gb"], 0.0)
self.assertGreater(p16_cuda["host_kv_gb"], 0.5)
p16_radeon_vis = inkling_fit.compute("SQ-15", 15.92, 64, 32768, vision=True, backend="hip")
self.assertFalse(p16_radeon_vis["full_vram"])
self.assertLessEqual(p16_radeon_vis["vram_gb"], 10.0)
@@ -0,0 +1,104 @@
"""Inkling-2-Mini fit planner: it works from the memory that is FREE (card and RAM), keeps a margin, keeps more beside a screen,
and writes the engine's flags in GiB (#6662 #6644 #6792 #6739). The numbers come from runs on an RTX 3060 12 GB, an A4000 16 GB and
an RTX 4090 24 GB (RESULTS-0221-INKCUDA.md): the engine's ledger showed 0.4-0.5 GiB of the card left after start-up at the old plans."""
from __future__ import annotations
import sys
import unittest
from pathlib import Path
from unittest import mock
TERMINAL = Path(__file__).resolve().parents[2]
if str(TERMINAL) not in sys.path:
sys.path.insert(0, str(TERMINAL))
import setup as S
from strata_control import inkling_fit as F
class FreeMemoryPlan(unittest.TestCase):
def test_vram_margin_is_taken_off_the_free_memory(self):
# a partial placement: every GiB of safety is a GB less in the card, the experts' rest goes to RAM
base = F.compute("SQ-15", 12.0, 64, 32768)
# a card with 0.3 GiB less free memory (the same plan made on what is really free) holds that much less
less = F.compute("SQ-15", 12.0 - F.VRAM_SAFETY_GB, 64, 32768)
self.assertAlmostEqual(base["vram_gb"] - less["vram_gb"], F.VRAM_SAFETY_GB * F.GIB_TO_GB, places=1)
self.assertGreater(F.VRAM_SAFETY_GB, 0.0)
def test_a_card_that_drives_a_screen_keeps_a_larger_reserve(self):
for build, vram in (("SQ-10", 8.0), ("SQ-15", 12.0)):
plain = F.compute(build, vram, 64, 32768)
shown = F.compute(build, vram, 64, 32768, desktop=True)
self.assertAlmostEqual(plain["vram_gb"] - shown["vram_gb"], F.DESKTOP_RESERVE_GB, places=2)
self.assertGreaterEqual(shown["ram_gb"], plain["ram_gb"]) # what leaves the card goes to RAM, not away
# the 8 GiB card of #6739: a real desktop reserve instead of 159 MiB
p8 = F.compute("SQ-10", 8.0, 31, 65536, desktop=True)
p8_plain = F.compute("SQ-10", 8.0, 31, 65536)
self.assertLessEqual(p8["vram_gb"], p8_plain["vram_gb"] - 0.75)
def test_free_ram_caps_the_experts_held_in_ram(self):
plenty = F.place("SQ-10", 4.0, 64, False, 32768)
self.assertGreater(plenty["ram_gb"], 8.0)
tight = F.place("SQ-10", 4.0, 64, False, 32768, ram_free_gib=6.0)
self.assertLessEqual(tight["ram_gb"], 6.0 * F.GIB_TO_GB - F.FREE_RAM_MARGIN_GB)
self.assertGreater(tight["ssd_gb"], 0.05) # what RAM cannot hold streams from disk: said, not overcommitted
# free RAM above the installed figure's own reserve changes nothing
same = F.place("SQ-10", 4.0, 64, False, 32768, ram_free_gib=60.0)
self.assertEqual(same["ram_gb"], plenty["ram_gb"])
def test_unknown_free_ram_keeps_the_old_rule(self):
self.assertEqual(F.place("SQ-10", 6.0, 32, False, 32768),
F.place("SQ-10", 6.0, 32, False, 32768, ram_free_gib=None))
def test_flags_are_gib_not_gb(self):
placed = {"vram_gb": 7.75, "ram_gb": 0.85}
got = S.inkling_expert_flags(placed)
self.assertEqual(got[0], "--vram-experts-gb")
self.assertEqual(got[2], "--ram-experts-gb")
self.assertAlmostEqual(float(got[1]), 7.75 / 1.073741824, places=2) # 7.22 GiB, not 7.75
self.assertAlmostEqual(float(got[3]), 0.85 / 1.073741824, places=2)
class SetupReadsFreeMemory(unittest.TestCase):
def test_ram_free_gb_linux_reads_memavailable(self):
meminfo = "MemTotal: 65843200 kB\nMemFree: 1000000 kB\nMemAvailable: 33554432 kB\n"
with mock.patch.object(S, "WIN", False), mock.patch.object(S.sys, "platform", "linux"), \
mock.patch("builtins.open", mock.mock_open(read_data=meminfo)), \
mock.patch.object(S, "_cgroup_memory_limit", return_value=None):
self.assertAlmostEqual(S.ram_free_gb(), 32.0, places=3)
def test_ram_free_gb_in_a_container_is_limited_by_the_cgroup(self):
meminfo = "MemTotal: 65843200 kB\nMemAvailable: 33554432 kB\n"
gib = 2 ** 30
real_open = open
def fake_open(name, *a, **k):
if str(name).endswith("memory.current"):
return mock.mock_open(read_data=str(14 * gib))()
if str(name) == "/proc/meminfo":
return mock.mock_open(read_data=meminfo)()
return real_open(name, *a, **k)
with mock.patch.object(S, "WIN", False), mock.patch.object(S.sys, "platform", "linux"), \
mock.patch("builtins.open", fake_open), mock.patch.object(S, "_cgroup_memory_limit", return_value=16 * gib):
self.assertAlmostEqual(S.ram_free_gb(), 2.0, places=3) # a 16 GiB limit with 14 GiB used
def test_plan_extra_carries_free_ram_and_the_display(self):
gpu = {"index": 0, "name": "NVIDIA GeForce RTX 3060", "vram_gb": 12.0, "free_gb": 11.0}
with mock.patch.object(S, "ram_free_gb", return_value=20.0), mock.patch.object(S, "gpu_drives_display", return_value=True):
self.assertEqual(S.inkling_plan_extra(gpu), {"ram_free_gib": 20.0, "desktop": True})
with mock.patch.object(S, "ram_free_gb", return_value=None), mock.patch.object(S, "gpu_drives_display", return_value=False):
self.assertEqual(S.inkling_plan_extra(gpu), {})
# a unified-memory machine has no card to keep a reserve on
with mock.patch.object(S, "ram_free_gb", return_value=20.0), mock.patch.object(S, "gpu_drives_display", return_value=True):
self.assertEqual(S.inkling_plan_extra({"index": 0, "uma": True}), {"ram_free_gib": 20.0})
def test_planner_input_is_min_of_total_and_free_vram(self):
gpu = {"index": 0, "name": "NVIDIA GeForce RTX 3060", "vram_gb": 12.0, "free_gb": 3.71, "arch": "86"}
vram, ram, unified, igpu, arch = S.inkling_pc(gpu, 64.0)
self.assertAlmostEqual(vram, 3.71, places=2)
self.assertFalse(unified)
if __name__ == "__main__":
unittest.main()