diff --git a/agent_local.py b/agent_local.py index 0db6c7d..46cc6ee 100644 --- a/agent_local.py +++ b/agent_local.py @@ -716,11 +716,20 @@ def choose_gpu(profile, family=None): return best -def recipe_gpu(profile, recipe, family=None, runtime=None, ctx=None): +def ranked_gpu_families(gpus): + """The best device per family, since setups and manifests identify the GPU by family.""" + ranked = {} + for gpu in sorted(gpus, key=gpu_rank, reverse=True): + ranked.setdefault(gpu["family"], gpu) + return ranked.values() + + +def recipe_gpu(profile, recipe, family=None, runtime=None, ctx=None, room_by_gpu=None): """The GPU a recipe runs on here: the one named, else the best of this machine's GPUs its runtime runs on that fits a variant (a pair machine still runs single-node recipes on its own - GPU, a CPU runtime runs on CPU even without a supported GPU, and when none fits it falls back - to the highest-ranked matching GPU so the caller reports that shortfall).""" + GPU, and a CPU runtime runs on CPU even without a supported GPU). New setups also check the + VRAM room on each candidate. Return the best static match if nothing has room, so the caller + can report its shortfall.""" if family: return choose_gpu(profile, family) if runtime is not None: @@ -733,17 +742,19 @@ def recipe_gpu(profile, recipe, family=None, runtime=None, ctx=None): if not matches and "cpu" in measured: return cpu_device(profile) if matches: - if recipe.get("variant"): - fitting = [] - for gpu in matches: - try: - if pick_variant(recipe, profile, gpu, ctx)[0] is not None: - fitting.append(gpu) - except LocalError: - pass - if fitting: - return max(fitting, key=gpu_rank) - return max(matches, key=gpu_rank) + static_match = None + for gpu in ranked_gpu_families(matches): + try: + variant = pick_variant(recipe, profile, gpu, ctx)[0] + except LocalError: + continue + if variant is None: + continue + if static_match is None: + static_match = gpu + if room_by_gpu is None or roomy_variant(recipe, variant, profile, gpu, room_by_gpu)[0] is not None: + return gpu + return static_match or max(matches, key=gpu_rank) return choose_gpu(profile) @@ -1611,22 +1622,31 @@ def local_held_vram_gib(gpu): return gib(held) -def roomy_variant(recipe, variant, profile, gpu): - """The variant to set up on a discrete card that something besides local models shares, such - as the desktop it drives. Fit goes by the card's size, so the largest variant can fit a card - and never what the desktop leaves of it: a 15 GiB variant on a 16 GB card whose desktop holds - 2. Stopping every local model wouldn't make that room, so the next variant at the same context - that fits what the card can give is the one to set up, and the first stays where none does.""" +def vram_room(gpu): + return free_memory(gpu)[1] + local_held_vram_gib(gpu) + + +def roomy_variant(recipe, variant, profile, gpu, room_by_gpu): + """Return the same-context variant a discrete card has room for, or explain the shortfall. + Room includes what local models can give back, but excludes what the desktop and other apps hold.""" if not discrete_gpu(gpu) or variant["peak_gpu_gib"] <= 0: - return variant - room = free_memory(gpu)[1] + local_held_vram_gib(gpu) + return variant, "" + # All recipes in a listing or recommendation share one snapshot per physical GPU. + key = id(gpu) + if key not in room_by_gpu: + room_by_gpu[key] = vram_room(gpu), False + room, rechecked = room_by_gpu[key] + if variant["peak_gpu_gib"] > room and not rechecked: + # A model can finish stopping after the free sample and before the holder scan. + room = vram_room(gpu) + room_by_gpu[key] = room, True if variant["peak_gpu_gib"] <= room: - return variant + return variant, "" for other in ordered_variants(recipe, gpu): if (other is not variant and other.get("ctx") == variant.get("ctx") and 0 < other["peak_gpu_gib"] <= room and fits(other, profile, gpu)[0]): - return other - return variant + return other, "" + return None, f"Needs {variant['peak_gpu_gib']:g} GiB VRAM on {gpu['family']}, with {room:g} GiB available after stopping local models" def match_class(best, profile, gpu, field="recipes"): @@ -1646,19 +1666,21 @@ def match_class(best, profile, gpu, field="recipes"): return max(same, key=lambda pair: pair[0], default=(0, None))[1] -def resolve_best(catalog, profile, gpu=None, ctx=None, field="recipes"): +def resolve_best(catalog, profile, gpu=None, ctx=None, field="recipes", room_by_gpu=None): """The first fitting recipe of the class of `gpu`, or, with none named, of this machine's GPUs from the strongest down: a pair's class first, then discrete GPUs, then integrated ones. `field` is the class's list to choose from: its text recipes, or another kind's list (BEST_FIELDS).""" + if room_by_gpu is None: + room_by_gpu = {} if gpu is not None: - return _resolve_class(catalog, profile, gpu, ctx, field) - gpus = sorted(profile["gpus"], key=gpu_rank, reverse=True) + return _resolve_class(catalog, profile, gpu, ctx, field, room_by_gpu) + gpus = ranked_gpu_families(profile["gpus"]) if not gpus: raise LocalError("No supported GPU found on this machine") failures = [] for candidate in gpus: try: - return _resolve_class(catalog, profile, candidate, ctx, field) + return _resolve_class(catalog, profile, candidate, ctx, field, room_by_gpu) except LocalError as error: failures.append((candidate, error)) # The most telling failure: the first GPU that has a recommendation at all. @@ -1666,7 +1688,7 @@ def resolve_best(catalog, profile, gpu=None, ctx=None, field="recipes"): raise classed[0] if classed else failures[0][1] -def _resolve_class(catalog, profile, gpu, ctx=None, field="recipes"): +def _resolve_class(catalog, profile, gpu, ctx, field, room_by_gpu): entry = match_class(catalog.best, profile, gpu, field) if entry is None and match_class(catalog.best, profile, gpu) is not None: kind = next((name for name, listed in BEST_FIELDS.items() if listed == field), field) @@ -1686,6 +1708,8 @@ def _resolve_class(catalog, profile, gpu, ctx=None, field="recipes"): except LocalError as error: # A requested context this recipe has no variant for passes to the next recommendation. variant, reason = None, str(error) + if variant and not recipe_installed(rid): + variant, reason = roomy_variant(catalog.recipes[rid], variant, profile, gpu, room_by_gpu) if variant: return rid, variant, skipped, gpu skipped.append((rid, reason)) @@ -1700,27 +1724,28 @@ def recipe_listing(catalog, profile, running=(), experimental=False, retired=Fal shown = {"experimental": experimental, "retired": retired} rows = [] ranks = {} - try: - gpu = choose_gpu(profile) - except LocalError as error: - gpu, gpu_error = None, str(error) + room_by_gpu = {} best_ids = set() - if gpu: + if profile["gpus"]: for field in BEST_FIELDS.values(): try: - best_ids.add(resolve_best(catalog, profile, field=field)[0]) + best_ids.add(resolve_best(catalog, profile, field=field, room_by_gpu=room_by_gpu)[0]) except LocalError: pass for rid in sorted(catalog.recipes): recipe = catalog.recipes[rid] - if any(recipe.get(flag) and not shown[flag] for flag in HIDDEN_FLAGS) and not recipe_installed(rid): + installed = recipe_installed(rid) + if any(recipe.get(flag) and not shown[flag] for flag in HIDDEN_FLAGS) and not installed: continue runtime = catalog.runtimes.get(recipe.get("runtime"), {}) - if gpu or runtime_is_cpu(runtime): - own = recipe_gpu(profile, recipe, runtime=runtime) - variant, reason = compatibility(catalog, rid, profile, own) + try: + own = recipe_gpu(profile, recipe, runtime=runtime, room_by_gpu=None if installed else room_by_gpu) + except LocalError as error: + own, variant, reason = None, None, str(error) else: - own, variant, reason = None, None, gpu_error + variant, reason = compatibility(catalog, rid, profile, own) + if variant and not installed: + variant, reason = roomy_variant(recipe, variant, profile, own, room_by_gpu) review = load_review(catalog, runtime) if runtime.get("tier") == "third-party" else {} measured = load_measurement(catalog, recipe, profile, own) if variant else {} kind = recipe_kind(recipe) @@ -1751,13 +1776,13 @@ def recipe_listing(catalog, profile, running=(), experimental=False, retired=Fal "publisher": review.get("publisher", ""), "vendor": recipe.get("vendor", ""), "architecture": recipe.get("architecture", ""), - "installed": recipe_installed(rid), + "installed": installed, "experimental": bool(recipe.get("experimental")), "retired": bool(recipe.get("retired")), "available": variant is not None, "reason": "" if variant else reason, # The recommendation of its kind: the agents' model, or the image model beside it. - "best": rid in best_ids, + "best": variant is not None and rid in best_ids, "active": rid in running, # What the card shows: the measured footprint (VRAM on discrete GPUs, RAM on unified/CPU), # host RAM needed, context and speed at a long prompt on this chip. @@ -4503,6 +4528,26 @@ def _lookup_recipe(catalog, target): return catalog.recipes[target] +def setup_device(catalog, rid, variant, profile, gpu, fresh, args): + recipe = catalog.recipes[rid] + room_by_gpu = {} + if fresh and args.target != "best" and not args.gpu: + runtime = catalog.runtimes[recipe["runtime"]] + selected = recipe_gpu(profile, recipe, runtime=runtime, ctx=args.ctx, room_by_gpu=room_by_gpu) + if selected is not gpu: + gpu = selected + variant, _ = compatibility(catalog, rid, profile, gpu, args.ctx) + roomy, reason = roomy_variant(recipe, variant, profile, gpu, room_by_gpu) + if roomy is None: + if fresh: + raise LocalError(reason) + return gpu, variant + if roomy is not variant: + say(f"Its largest setup needs {variant['peak_gpu_gib']:g} GiB of the GPU's memory, more than what else uses the card leaves: " + f"setting up the one sized for {roomy['peak_gpu_gib']:g} GiB") + return gpu, roomy + + def cmd_use(argv): parser = argparse.ArgumentParser(prog="omarchy models use") parser.add_argument("target", help="best, or a recipe id") @@ -4543,22 +4588,16 @@ def cmd_use(argv): say(f"{rid} is experimental: kept for trying, and not recommended for any machine") elif recipe.get("retired"): say(f"{rid} is retired: no longer offered or recommended, and kept so a setup of it keeps working") - roomy = roomy_variant(catalog.recipes[rid], variant, profile, gpu) - if roomy is not variant: - say(f"Its largest setup needs {variant['peak_gpu_gib']:g} GiB of the GPU's memory, more than what else uses the card leaves: " - f"setting up the one sized for {roomy['peak_gpu_gib']:g} GiB") - variant = roomy - measured_load = load_measurement(catalog, catalog.recipes[rid], profile, gpu).get("load_seconds") - # Before a detached setup leaves this process, so polkit can still ask in the user's session. - raise_gpu_memory(variant, gpu, args.detach) + recipe = catalog.recipes[rid] if args.detach: - return detach_use(rid, args, catalog.recipes[rid], measured_load, gpu=gpu, variant=variant) + return detach_use(rid, args, catalog, profile, gpu, variant) + measured_load = load_measurement(catalog, recipe, profile, gpu).get("load_seconds") + fresh = load_model(rid) is None # A first setup shows in the panel from now on: waiting for the lock, then # downloading, then loading once activate() writes its pending row. - fresh = load_model(rid) is None if fresh: if installing_idle(rid): - begin_installing(rid, catalog.recipes[rid], measured_load) + begin_installing(rid, recipe, measured_load) # The process carrying the setup is the one remove signals, from now on, # so a setup waiting for another's lock can be cancelled too. A second use # of the same recipe leaves a live owner in place; a detached unit takes @@ -4568,14 +4607,22 @@ def cmd_use(argv): update_installing(rid, pid=os.getpid()) try: with Lock(): - if fresh and load_model(rid) is None and load_installing(rid) is None: + first_setup = load_model(rid) is None + if fresh and first_setup and load_installing(rid) is None: # remove cleared its record while it waited: nothing to fetch. raise LocalError(f"The setup of {rid} was cancelled") if fresh: # Whoever holds the lock does the work, so it is the one remove signals: # a queued retry takes over from the attempt that failed before it. update_installing(rid, pid=os.getpid()) - return _use_setup(rid, variant, args, catalog, profile, gpu, fresh, measured_load) + # VRAM may have changed while the detached unit started or this setup waited for the lock. + selected, variant = setup_device(catalog, rid, variant, profile, gpu, first_setup, args) + if selected is not gpu: + measured_load = load_measurement(catalog, recipe, profile, selected).get("load_seconds") + if first_setup: + update_installing(rid, expected_load_seconds=measured_load) + raise_gpu_memory(variant, selected) + return _use_setup(rid, variant, args, catalog, profile, selected, fresh, measured_load) except KeyboardInterrupt: # A caller still waiting on another's setup leaves that setup's record alone. if fresh and load_model(rid) is None and owns_installing(rid): @@ -4588,15 +4635,21 @@ def cmd_use(argv): raise -def detach_use(rid, args, recipe, measured_load=None, gpu=None, variant=None): +def detach_use(rid, args, catalog, profile, gpu, variant): """Run the setup as a transient user unit, so it outlives the panel or terminal that asked for it; its output goes to the journal.""" unit = install_unit(rid) if systemctl("is-active", "--quiet", unit).returncode == 0: say(f"{rid} is already being set up; follow it with: journalctl --user -u {unit} -f") return 0 + fresh = load_model(rid) is None + gpu, variant = setup_device(catalog, rid, variant, profile, gpu, fresh, args) + # Before the setup leaves this process, so polkit can still ask in the user's session. + raise_gpu_memory(variant, gpu, detach=True) systemctl("reset-failed", unit) - if load_model(rid) is None and installing_idle(rid): + if fresh and installing_idle(rid): + recipe = catalog.recipes[rid] + measured_load = load_measurement(catalog, recipe, profile, gpu).get("load_seconds") begin_installing(rid, recipe, measured_load) entry = ENGINE command = ["systemd-run", "--user", "--collect", "--quiet", f"--unit={unit}", f"--description=Set up local model {rid}"] @@ -4610,10 +4663,10 @@ def detach_use(rid, args, recipe, measured_load=None, gpu=None, variant=None): if env.get(name): command.append(f"--setenv={name}") command += [entry, "use", rid] - ctx = args.ctx or (variant.get("ctx") if variant else None) + ctx = args.ctx or variant.get("ctx") if ctx: command += ["--ctx", str(ctx)] - gpu_family = args.gpu or (gpu.get("family") if gpu and gpu.get("family") != "cpu" else None) + gpu_family = args.gpu or (gpu["family"] if gpu["family"] != "cpu" else None) if gpu_family: command += ["--gpu", gpu_family] if args.seed: diff --git a/docs/engine.md b/docs/engine.md index 6245f16..42e661b 100644 --- a/docs/engine.md +++ b/docs/engine.md @@ -85,12 +85,12 @@ rejected. `validate ` checks the records and referenced evidence; class's recipes of that kind (`recipes` for text, else `images`, `videos` or `music` in `best.toml`) in order; `use best` alone lists each kind's pick for this machine and sets nothing up. It checks that the runtime runs on the GPU and that the recipe fits, and chooses the largest fitting context, and at the same context the variant with the larger memory peak that fits. -Fit goes by a card's size, so on a discrete GPU that something else shares, such as the desktop it drives, `use` then checks what the card can give: its free VRAM and what running local models hold. Where the chosen variant needs more, it sets up the next one at the same context that fits that room, and the manifest keeps it (`variant_for_room`) so the larger variant isn't offered as an update. +On a discrete GPU that something else shares, such as the desktop it drives, `list` and `use` check what the card can give a new setup: free VRAM plus what local models would give back if stopped. Where the chosen variant needs more, they pick the next one at the same context that fits that room, and the setup manifest keeps it (`variant_for_room`) so the larger variant isn't offered as an update. Without `--gpu`, a new setup can use another compatible GPU family with room. If no candidate fits, `list` reports the shortfall and `use` stops before downloading. `use best` goes on to the next recommendation. These checks leave running models alone. A GPU class is its family, except that the N1x (`nvidia-n1x`) shares the GB10's (`nvidia-gb10`): the same chip, so what either can run depends only on memory. Discrete NVIDIA GPUs are detected through `nvidia-smi` on non-unified platforms and report free VRAM from the driver; an AMD GPU with 4 GiB or more of VRAM is a discrete card, judged by its VRAM alone (what spills into GTT runs from system RAM, too slow to count), with free VRAM from sysfs and the VRAM a model holds from its processes' fdinfo. An Intel Arc card on xe (any xe device but integrated graphics at 00:02.0) is one too: xe gives its VRAM size and use only through its memory-region query (`DRM_XE_DEVICE_QUERY_MEM_REGIONS`), which needs no privilege, and a model's share from `drm-resident-vram0` in fdinfo. A variant whose `peak_ram_gib` is below its `peak_gpu_gib` is sized for a discrete card's own VRAM: unified GPUs, whose GPU memory is RAM, never pick it, and a discrete GPU prefers it at the same context; unified AMD iGPUs with fewer than 8 Compute Units (such as 2-CU display iGPUs like the Radeon 610M) are excluded. When a machine has multiple GPUs, pairs outrank single nodes and discrete GPUs outrank integrated ones regardless of GTT size. Measurements keep the family they ran on. `use ` supports `--ctx`, `--gpu`, -`--seed`. Two questions decide which recipes a machine is offered (`list`'s `available`): whether -the runtime's image works on the GPU (its `gpus`) and whether a variant fits the GPU's memory and -RAM. A measurement on the machine's class is not needed; it gives the panel speeds to show, and +`--seed`. A recipe is offered (`list`'s `available`) when the runtime's image works on the GPU (its `gpus`) +and a variant fits the GPU's memory and RAM, including the discrete VRAM check for new setups. +A measurement on the machine's class is not needed; it gives the panel speeds to show, and `best.toml`, kept by hand and only for measured classes, decides what is recommended. Admission also checks current free RAM and GPU memory and reserves 8 GiB for the desktop. An Intel GPU is integrated graphics on the `xe` kernel driver (Lunar Lake and newer), named by diff --git a/tests/engine-test.sh b/tests/engine-test.sh index 7808d9b..de92d67 100755 --- a/tests/engine-test.sh +++ b/tests/engine-test.sh @@ -284,7 +284,7 @@ card_profile = dict(big_card, gpus=[card_16]) def roomy(recipe, variant, free_vram, held=0.0, gpu=card_16, profile=card_profile): with (patch.object(a, "free_memory", return_value=(40.0, free_vram)), patch.object(a, "local_held_vram_gib", return_value=held)): - return a.roomy_variant(recipe, variant, profile, gpu) + return a.roomy_variant(recipe, variant, profile, gpu, {})[0] check("a card with room for the largest variant keeps it, counting what running models would free", a.pick_variant(shared_card, card_profile, card_16)[0] is full_variant and roomy(shared_card, full_variant, 15.2) is full_variant @@ -292,13 +292,17 @@ check("a card with room for the largest variant keeps it, counting what running check("a card whose desktop leaves less than the largest variant needs takes the next one that fits the room", roomy(shared_card, full_variant, 13.6) is offload_variant and roomy(shared_card, full_variant, 6.6, held=7.0) is offload_variant) -check("the largest variant stays where no other fits the room, the RAM, or the same context", - roomy(shared_card, full_variant, 5.0) is full_variant - and roomy(shared_card, full_variant, 13.6, profile=dict(card_profile, ram_gib=16)) is full_variant - and roomy(text_both, text_both["variant"][1], 13.6) is text_both["variant"][1] - and roomy({"variant": [dict(full_variant, ctx=65536), dict(offload_variant, ctx=32768)]}, full_variant, 13.6) is full_variant) +check("no variant is chosen where no other fits the room, the RAM, or the same context", + roomy(shared_card, full_variant, 5.0) is None + and roomy(shared_card, full_variant, 13.6, profile=dict(card_profile, ram_gib=16)) is None + and roomy(text_both, text_both["variant"][1], 13.6) is None + and roomy({"variant": [dict(full_variant, ctx=65536), dict(offload_variant, ctx=32768)]}, full_variant, 13.6) is None) check("a unified GPU, whose desktop shares its RAM by design, is left alone", roomy(shared_card, full_variant, 13.6, gpu=found_amd[1], profile=apu_profile) is full_variant) +with (patch.object(a, "free_memory", side_effect=[(40, 10), (40, 15.2)]), + patch.object(a, "local_held_vram_gib", return_value=0)): + check("VRAM is sampled again if a local model finishes stopping during the check", + a.roomy_variant(shared_card, full_variant, card_profile, card_16, {})[0] is full_variant) with (patch.object(a, "known_models", return_value=["running", "stopping", "idle"]), patch.object(a, "unit_props", side_effect=lambda rid, *_: { "running": {"ActiveState": "active", "ControlGroup": "/running"}, @@ -515,6 +519,73 @@ dgpu_cat = SimpleNamespace( dgpu_rows = a.recipe_listing(dgpu_cat, dgpu_profile) check("recipe_listing reports peak_gpu_gib and memory_kind=vram on a discrete GPU", len(dgpu_rows) == 1 and dgpu_rows[0]["memory_gib"] == 8 and dgpu_rows[0]["memory_kind"] == "vram", str(dgpu_rows)) + +# The shipped Inkling setups on the discrete cards reported in #200 and Omarchy #21729. +inkling_catalog = a.load_catalog() +for card, rid, ctx, need, busy, free in ( + (dict(card_16, family="amd-gfx1201"), "inkling-2-mini-llamacpp", 65536, 15, 13.6, 15.2), + (nv_cards[1], "inkling-2-mini-llamacpp-cuda", 131072, 23.3, 17.7, 23.5), +): + simulated = dict(dgpu_profile, ram_gib=32, ram_class=32, gpus=[card]) + short = f"Needs {need:g} GiB VRAM on {card['family']}, with {busy:g} GiB available after stopping local models" + with (patch.object(a, "load_catalog", return_value=inkling_catalog), + patch.object(a, "machine_profile", return_value=simulated), + patch.object(a, "free_memory", return_value=(25, busy)) as memory, + patch.object(a, "local_held_vram_gib", return_value=0) as held, + patch.object(a, "raise_gpu_memory"), + patch.object(a, "_use_setup", return_value=0) as setup, + patch.object(a, "systemctl", return_value=SimpleNamespace(returncode=3)) as control, + patch.object(a.subprocess, "run", return_value=SimpleNamespace(returncode=0)) as spawn): + row = next(row for row in a.recipe_listing(inkling_catalog, simulated) if row["id"] == rid) + check(f"{card['family']} does not offer Inkling with too little VRAM", + not row["available"] and not row["best"] and row["reason"] == short) + check("a listing reads the selected GPU at most twice", + 1 <= memory.call_count == held.call_count <= 2 + and all(call.args[0] is card for call in memory.call_args_list + held.call_args_list)) + raises(f"{card['family']} rejects a detached setup before spawning", lambda: a.cmd_use([rid, "--detach"]), short) + check("a rejected detached setup leaves no install record", not spawn.called and a.load_installing(rid) is None) + control.return_value.returncode = 0 + check("a detached setup already under way keeps running even if room is now low", + a.cmd_use([rid, "--detach"]) == 0 and not spawn.called) + control.return_value.returncode = 3 + raises(f"{card['family']} rejects a foreground setup before downloading", lambda: a.cmd_use([rid]), short) + check("a rejected foreground setup records the failure and never enters setup", + not setup.called and a.load_installing(rid)["error"] == short and a.load_model(rid) is None) + a.clear_installing(rid) + memory.return_value = (25, free) + row = next(row for row in a.recipe_listing(inkling_catalog, simulated) if row["id"] == rid) + check(f"{card['family']} offers Inkling once it has room", row["available"] and row["context"] == ctx) + check("enough free VRAM allows setup to be handed off", a.cmd_use([rid, "--detach"]) == 0 and spawn.called) + memory.return_value = (25, busy) + held.return_value = free - busy + check("reclaimable local-model VRAM allows the setup to proceed", + a.cmd_use([rid, "--gpu", card["family"]]) == 0 + and setup.call_args.args[1]["peak_gpu_gib"] == need and setup.call_args.args[5] is card) + a.clear_installing(rid) + +primary_cuda = dict(nv_cards[1], family="nvidia-rtx5090", memory_gib=32, vram_gib=32, vram_class=32, compute_cap="12.0") +secondary_cuda = dict(nv_cards[1], family="nvidia-rtx5090-laptop", compute_cap="12.0") +dual_cuda = dict(dgpu_profile, gpus=[primary_cuda, secondary_cuda]) +with (patch.object(a, "load_catalog", return_value=inkling_catalog), + patch.object(a, "machine_profile", return_value=dual_cuda), + patch.object(a, "free_memory", side_effect=lambda gpu: (25, 20 if gpu is primary_cuda else 23.5)), + patch.object(a, "local_held_vram_gib", return_value=0), + patch.object(a, "_use_setup", return_value=0) as setup, + patch.object(a, "systemctl", return_value=SimpleNamespace(returncode=3)), + patch.object(a.subprocess, "run", return_value=SimpleNamespace(returncode=0)) as spawn): + rid = "inkling-2-mini-llamacpp-cuda" + row = next(row for row in a.recipe_listing(inkling_catalog, dual_cuda) if row["id"] == rid) + check("the available CUDA build can be recommended on a secondary GPU", row["available"] and row["best"]) + check("bare use chooses the idle compatible GPU", + a.cmd_use([rid]) == 0 and setup.call_args.args[5] is secondary_cuda) + a.clear_installing(rid) + check("use best --detach passes the idle GPU to the worker", + a.cmd_use(["best", "text", "--detach"]) == 0 and spawn.call_args.args[0][-2:] == ["--gpu", secondary_cuda["family"]]) + a.clear_installing(rid) + raises("an explicit busy GPU doesn't fall back to another card", lambda: a.cmd_use([rid, "--gpu", primary_cuda["family"]]), + "Needs 23.3 GiB VRAM on nvidia-rtx5090, with 20 GiB available") + a.clear_installing(rid) + with patch.object(a, "_nvidia_smi", return_value=["16384"]), patch.object(a, "meminfo", return_value={"MemTotal": 128 * 2**30, "MemAvailable": 100 * 2**30}): dgpu_status = a.status_record(dgpu_cat, dgpu_profile) check("status_record reports vram_total_gib, vram_free_gib and vram_device on a discrete NVIDIA GPU", @@ -2036,14 +2107,16 @@ check("removing a model with a cancelled background update drops its pull temp d # --detach hands the setup to a transient user unit and returns. a.clear_installing(rid) +detached_gpu = a.cpu_device(profile) +detached_variant = {"peak_gpu_gib": 0} with patch.object(a, "systemctl", return_value=SimpleNamespace(returncode=3)), patch.object(a, "load_model", return_value=None), patch.object(a.subprocess, "run", return_value=SimpleNamespace(returncode=0, stdout="", stderr="")) as run: - check("a detached setup returns at once", a.detach_use(rid, SimpleNamespace(ctx=8192, gpu=None, seed=None), cat.recipes[rid]) == 0) + check("a detached setup returns at once", a.detach_use(rid, SimpleNamespace(target="best", ctx=8192, gpu=None, seed=None), cat, profile, detached_gpu, detached_variant) == 0) argv = run.call_args.args[0] check("a detached setup runs use in its own user unit", argv[:3] == ["systemd-run", "--user", "--collect"] and f"--unit={a.install_unit(rid)}" in argv and argv[-4:-2] == ["use", rid] and argv[-2:] == ["--ctx", "8192"], " ".join(argv)) check("a detached setup is listed before its unit starts", a.load_installing(rid)["phase"] == "waiting") a.clear_installing(rid) with patch.dict(os.environ, {"HF_TOKEN": "hf_secret_value", "OMARCHY_LOCAL_AI_CATALOG": "relative/catalog"}), patch.object(a, "systemctl", return_value=SimpleNamespace(returncode=3)), patch.object(a, "load_model", return_value=None), patch.object(a.subprocess, "run", return_value=SimpleNamespace(returncode=0, stdout="", stderr="")) as run: - a.detach_use(rid, SimpleNamespace(ctx=None, gpu=None, seed=None), cat.recipes[rid]) + a.detach_use(rid, SimpleNamespace(target="best", ctx=None, gpu=None, seed=None), cat, profile, detached_gpu, detached_variant) argv, env = run.call_args.args[0], run.call_args.kwargs["env"] check("a detached setup never puts the token on a command line", not any("hf_secret_value" in arg for arg in argv) and "--setenv=HF_TOKEN" in argv and env["HF_TOKEN"] == "hf_secret_value") check("a detached setup gets the catalog as an absolute path", env["OMARCHY_LOCAL_AI_CATALOG"] == os.path.abspath("relative/catalog"))