diff --git a/docs/capacity-planning.md b/docs/capacity-planning.md index 38d89072..38971e0c 100644 --- a/docs/capacity-planning.md +++ b/docs/capacity-planning.md @@ -16,6 +16,15 @@ other architecture modules are included in the inventory. Unequal devices receiv placement according to their individual budgets. A large device cannot cover a shortfall on a smaller device. +Planning follows the execution device: `--device auto` can use all supplied GPU +budgets, while `--device cuda` or `cuda:N` confines the model to that visible +ordinal. Budgets remain in visible order, so selecting `cuda:1` requires entries +for ordinals 0 and 1. CPU commands use `--plan-host-memory` for execution and do +not require `--plan-free-memory`. Explicit devices cannot acquire a different +placement through `--plan-offload` or `--device-map`. Unsupported execution +backends refuse a capacity claim. Supply budgets for the allocation after any +GPU visibility selection. + Dry-runs apply `OBLITERATUS_DEVICE_MEMORY_CEILINGS`, including the host ceiling; the qualification driver's `--device-ceilings` JSON takes precedence over that environment setting. `--gpu-memory-utilization` scales the supplied free GPU @@ -71,6 +80,9 @@ length. KV cache depends on key/value head count, head width, layer ownership an the prompt plus generation length. Edit workspace depends on the largest logical weight being edited. Eager attention needs a sequence-squared workspace reserve; changing its implementation changes the estimate and must be recorded. +Config-enabled `output_attentions` and `output_hidden_states` are included in +forward peaks because activation collection inherits those settings. Their +retained outputs accumulate across decoder layers. For each phase, the peak includes resident weights and the phase's temporary components, with safety headroom. Loading, baseline evaluation, activation @@ -104,6 +116,12 @@ conservative bound even when no reference is selected. For Qwen2.5-72B, 100,000 comparison prompts require about 56.65 GiB per set before token IDs; a 32 GiB host budget is refused before loading weights. Both preparation and `--plan-only` count the selected workload's comparison list, including fixture defaults. +Disk admission also reserves both workers' observation files: four comparison +sets in total, plus their activation means and directions. This conservative +bound also applies when no reference is selected. Completed reference files are +already charged by current free space during execution rechecks; reload creates +no new observation file. A staged 32B BF16 workload with 100,000 comparison +prompts is refused with 150 GiB of free disk even when host memory suffices. Gated concept probes retain three auxiliary readouts alongside the primary positive/control activations. This includes `concepts baseline`, which uses @@ -165,6 +183,8 @@ is an alias for `--plan-only`. The qualification driver's `--device-map map.json` validates that exact placement against the supplied budgets in a dry-run. Without a map, the planner chooses a whole-block placement from those budgets. +Hardware dry-runs require exactly `--devices` GPU budgets. Rehearsal dry-runs +estimate CPU execution; their device count remains synthetic. The same flags are available on `obliterate`/`abliterate`, concept `baseline` and `steer`, and the three Pain-Axis scripts. They stop before model, direction @@ -179,6 +199,10 @@ python -m obliteratus obliterate Qwen/Qwen2.5-72B-Instruct \ --plan-batch-size 1 --plan-sequence-length 512 --plan-generation-tokens 120 ``` +Concept `baseline` and `steer` default to CPU placement, matching execution. +The Pain-Axis scripts plan their fixed single-device `cuda:0` execution; +additional GPU budgets do not enable splitting those runs. + Primary `obliterate`/`abliterate` plans default to a sibling of the checkpoint directory: the example writes `evidence/72b-concept-plan.capacity-plan.json`. This keeps the plan when a successful run atomically replaces that checkpoint diff --git a/obliteratus/capacity_planning.py b/obliteratus/capacity_planning.py index 34fc4cf3..f822ff95 100644 --- a/obliteratus/capacity_planning.py +++ b/obliteratus/capacity_planning.py @@ -12,7 +12,7 @@ import re from dataclasses import asdict, dataclass from pathlib import Path -from obliteratus.qualification import canonical_json, parameter_device, validate_plan +from obliteratus.qualification import canonical_json, normalize_device, parameter_device, validate_plan GIB = 1024**3 PHASES = ("load", "baseline", "activations", "direction", "edit", "verify", "save", "reload") @@ -185,7 +185,7 @@ def _forward(inventory, mapping, workload, *, cached): output = execution if output in {"cpu", "disk"} else output options = dict(batch_size=workload.batch_size, dtype_bytes=inventory["dtype_bytes"], resident_bytes={}, largest_tensor_bytes=staging, input_device=entry, output_device=output, - attention_mask=True, output_attentions=False, output_hidden_states=False, + attention_mask=True, mamba_scan_backend="torch") demands = [transformer_demands(cfg, placement, tokens=workload.sequence_length, use_cache=cached, cache_tokens=workload.sequence_length, @@ -238,7 +238,7 @@ def plan_capacity(inventory: dict, free_memory: dict[str, int], *, workload: Wor mapping = _module_map(inventory, devices, offload) base = dict(mapping, **{block: devices[0] for block in blocks}) forward = _forward(inventory, base, workload, cached=True) - # Forward temporaries are sequential; only KV storage grows with layer count. + # Config-enabled return tensors accumulate alongside per-layer KV storage. overhead = max((sum(value.values()) - value.get("kv_cache", 0) for value in forward.values()), default=0) cfg = inventory["text_config"] hidden = cfg["hidden_size"] @@ -247,6 +247,10 @@ def plan_capacity(inventory: dict, free_memory: dict[str, int], *, workload: Wor + workload.neighbour_samples) * len(blocks) * hidden * 4 comparison_bytes = workload.comparison_prompts * (cfg["vocab_size"] * 4 + (workload.sequence_length + workload.generation_tokens) * 8) + # Both edit and reference workers persist stock/edited outputs, activation + # means and directions. Reserve both files even when no reference is selected. + observation_disk = (4 * comparison_bytes + 4 * len(blocks) * hidden * 4 + if workload.comparison_prompts else 0) # Distillation concatenates every primary layer while the chunks remain live. # Validation materializes all readouts, then retains their FP64 copies. materialization = max(workload.activation_datasets * dataset_bytes if workload.concept_extraction else 0, @@ -436,6 +440,8 @@ def plan_capacity(inventory: dict, free_memory: dict[str, int], *, workload: Wor "output_and_staging": 0 if reload else 2 * inventory["total_weight_bytes"], "offload": resident.get("disk", 0), "snapshot": 0 if reload else snapshot_disk, "reserve": host_reserve_bytes} + if observation_disk and not reload: + disk_components["qualification_observations"] = observation_disk disk_peak = sum(disk_components.values()) rows["disk"] = {"components": disk_components, "peak_bytes": disk_peak, "budget_bytes": disk_memory_bytes, "headroom_bytes": disk_memory_bytes - disk_peak} @@ -469,7 +475,8 @@ def plan_capacity(inventory: dict, free_memory: dict[str, int], *, workload: Wor "Qualification comparison outputs retain FP32 vocabulary rows and generated token IDs", "Default surgery includes the LM head and excludes input embeddings; offloaded edits retain host overlays", "Source shard bound is operator supplied without an index; index grouping otherwise", - "Disk includes download, prior output, staging, offload and optional snapshot", + "Config-enabled attention and hidden-state outputs remain live through forwards", + "Disk includes download, prior output, staging, offload, optional snapshot and both qualification observation files", "Runtime free-memory admission and realized export eligibility remain required"]} @@ -557,7 +564,7 @@ def _plan_prompt_counts(args): def maybe_plan(args, model_name: str, *, dtype=None, sequence_length=None, batch_size=None, generation_tokens=None, unsupported_reason=None, concept_edit=False, - activation_datasets=2, collection_copies=0): + activation_datasets=2, collection_copies=0, device=None, uses_device_map=False): if not getattr(args, "plan_only", False): return None source = getattr(args, "plan_config", None) or Path(model_name) @@ -565,7 +572,14 @@ def maybe_plan(args, model_name: str, *, dtype=None, sequence_length=None, batch source = source / "config.json" if source.is_dir() else source if not source.is_file(): raise ValueError("plan-only requires a local --plan-config JSON; weights and remote metadata are never downloaded") - for name in ("plan_free_memory", "plan_host_memory", "plan_disk_memory"): + execution_device = device if device is not None else getattr(args, "device", "auto") + execution_device = "cuda:0" if execution_device == "cuda" else execution_device + if execution_device not in {"auto", "cpu"} and not re.fullmatch(r"cuda:\d+", execution_device): + raise ValueError(f"no capacity contract for execution device {execution_device!r}") + required = ["plan_host_memory", "plan_disk_memory"] + if execution_device != "cpu": + required.append("plan_free_memory") + for name in required: if getattr(args, name, None) is None: raise ValueError(f"plan-only requires --{name.replace('_', '-')}") @@ -626,18 +640,31 @@ def maybe_plan(args, model_name: str, *, dtype=None, sequence_length=None, batch if utilization is not None and (isinstance(utilization, bool) or not isinstance(utilization, (int, float)) or not math.isfinite(utilization) or not 0 < utilization <= 1): raise ValueError("gpu_memory_utilization must be finite and within (0, 1]") - budgets = {f"cuda:{i}": bytes_from_gib(value) for i, value in enumerate(args.plan_free_memory)} + budgets = {f"cuda:{i}": bytes_from_gib(value) for i, value in enumerate(args.plan_free_memory or [])} + if execution_device.startswith("cuda:"): + if execution_device not in budgets: + raise ValueError(f"--plan-free-memory must include the visible-order budget for {execution_device}") + budgets = {execution_device: budgets[execution_device]} # Planning precedes CUDA initialization in a fresh process. Scaling free # bytes also bounds qualification's fraction of total bytes conservatively. for device, free in budgets.items(): budgets[device] = min(free, ceilings.get(device, free), int(free * utilization) if utilization is not None else free) host = min(bytes_from_gib(args.plan_host_memory), ceilings.get("cpu", 2**63)) + if execution_device == "cpu": + budgets = {"cpu": host} + offload = args.plan_offload if args.plan_offload is not None else getattr(args, "offload", "none") + if execution_device != "auto" and not uses_device_map: + if offload != "none": + limitations.append("Explicit execution devices do not use CPU/disk offload; a separate placement is not admitted") + offload = "none" + if device_map is not None and any(normalize_device(value) != execution_device for value in device_map.values()): + raise ValueError("device map conflicts with the requested execution device") plan = plan_capacity(inventory, budgets, workload=workload, host_memory_bytes=host, disk_memory_bytes=bytes_from_gib(args.plan_disk_memory), device_map=device_map or None, source_shard_bytes=bytes_from_gib(args.plan_source_shard_gib), - offload=args.plan_offload if args.plan_offload is not None else getattr(args, "offload", "none"), + offload=offload, **snapshot_options(args), concept_edit=concept_edit or bool(getattr(args, "concept", None) not in {None, "refusal"} or getattr(args, "preserve", None)), @@ -645,6 +672,7 @@ def maybe_plan(args, model_name: str, *, dtype=None, sequence_length=None, batch quantization=getattr(args, "quantization", None), unsupported_reason="; ".join(limitations) or None) plan["metadata_source"] = {"config": str(source), "config_kind": "local_json", "weights_loaded": False} + plan["execution_device"] = execution_device plan["assumptions"].append("Fresh process with no existing accelerator reservations; utilization scales supplied free bytes") print_plan(plan) if args.plan_output: diff --git a/obliteratus/qualification_runtime.py b/obliteratus/qualification_runtime.py index 2741ad96..4947435f 100644 --- a/obliteratus/qualification_runtime.py +++ b/obliteratus/qualification_runtime.py @@ -352,6 +352,10 @@ def _load(source: Path, configuration: dict, plan: dict, offload_directory: Path # already charged by current free space; keep the fresh export. completed = configuration.get("completed_reference_export_bytes", 0) required -= min(completed, admitted_capacity.get("total_weight_bytes", 0)) + observations = offload_directory.parent / "reference-observations.safetensors" + if completed and observations.is_file(): + observation_budget = admitted_capacity["phases"]["save"]["disk"]["components"].get("qualification_observations", 0) + required -= min(observations.stat().st_size, observation_budget // 2) if required > available[device]: raise ValueError(f"{device} no longer has the frozen capacity plan's phase headroom") budgets = available diff --git a/scripts/gpu_qualification.py b/scripts/gpu_qualification.py index 048d4515..b3e8f1a5 100644 --- a/scripts/gpu_qualification.py +++ b/scripts/gpu_qualification.py @@ -295,8 +295,11 @@ def main(argv=None) -> int: from obliteratus.capacity_planning import CapacityPlanningError, maybe_plan args.plan_output = args.plan_output or args.output.with_name(args.output.name + ".capacity-plan.json") + if args.mode == "hardware" and args.plan_free_memory is not None and len(args.plan_free_memory) != args.devices: + raise ValueError("--plan-free-memory must supply exactly --devices visible-order GPU budgets") try: maybe_plan(args, str(args.model or args.plan_config or ""), dtype=args.dtype, + device="cpu" if args.mode == "rehearsal" else "auto", uses_device_map=True, sequence_length=32, batch_size=4, generation_tokens=args.generation_tokens) except CapacityPlanningError as exc: print(str(exc), file=sys.stderr) diff --git a/scripts/pain_axis_appendix_d.py b/scripts/pain_axis_appendix_d.py index 1729bd54..819539ed 100644 --- a/scripts/pain_axis_appendix_d.py +++ b/scripts/pain_axis_appendix_d.py @@ -150,7 +150,7 @@ def run(args): if getattr(args, "plan_only", False): if args.plan_output is None: args.plan_output = Path(args.out) / "capacity-plan.json" - return maybe_plan(args, args.model, dtype="bfloat16", batch_size=args.batch_size, concept_edit=True, + return maybe_plan(args, args.model, dtype="bfloat16", device="cuda:0", batch_size=args.batch_size, concept_edit=True, generation_tokens=max(args.max_new_tokens, args.refusal_eval_max_new_tokens)) source = ConceptDirection.load(args.direction) diff --git a/scripts/pain_axis_refusal_recovery.py b/scripts/pain_axis_refusal_recovery.py index a8ed0411..35d51a08 100644 --- a/scripts/pain_axis_refusal_recovery.py +++ b/scripts/pain_axis_refusal_recovery.py @@ -82,7 +82,7 @@ def run(args): output = Path(args.out) args.plan_output = output.with_name(output.name + ".capacity-plan.json") return maybe_plan( - args, args.model, dtype="bfloat16", batch_size=1, sequence_length=args.max_length, concept_edit=True, + args, args.model, dtype="bfloat16", device="cuda:0", batch_size=1, sequence_length=args.max_length, concept_edit=True, generation_tokens=max(args.humor_tokens, args.refusal_tokens, args.distill_tokens), unsupported_reason="Recovery training memory is not modelled; " "this is an inference capacity estimate only", diff --git a/scripts/pain_axis_replication.py b/scripts/pain_axis_replication.py index 749db174..f858c4fc 100644 --- a/scripts/pain_axis_replication.py +++ b/scripts/pain_axis_replication.py @@ -560,7 +560,7 @@ def main(argv=None): if args.plan_output is None: args.plan_output = Path(args.out) / "capacity-plan.json" try: - maybe_plan(args, args.model, dtype="bfloat16", batch_size=8 if args.stage == "ablate" else 1, + maybe_plan(args, args.model, dtype="bfloat16", device="cuda:0", batch_size=8 if args.stage == "ablate" else 1, generation_tokens=120 if args.stage == "resteer" else 60, activation_datasets=len(VECTOR_DATASETS) if args.stage == "vectors" else 2, collection_copies=2 if args.stage == "vectors" else 0, diff --git a/tests/test_capacity_entry_points.py b/tests/test_capacity_entry_points.py index 167e47c9..1157cab6 100644 --- a/tests/test_capacity_entry_points.py +++ b/tests/test_capacity_entry_points.py @@ -100,6 +100,37 @@ def test_primary_plan_preserves_explicit_evidence_path(tmp_path, monkeypatch, pl assert planned.call_args.args[0].plan_output == evidence +@pytest.mark.parametrize("command", ["obliterate", "abliterate"]) +@pytest.mark.parametrize("device", ["auto", "cuda", "cuda:0", "cuda:1", "cpu"]) +def test_primary_plan_respects_execution_device(tmp_path, monkeypatch, planning_only, command, device): + monkeypatch.setattr(cli, "_apply_gpu_selection", planning_only) + monkeypatch.setattr(cli, "_cmd_abliterate", planning_only) + source = Path(__file__).parent / "fixtures" / "capacity_configs" / "qwen2.5-72b-instruct.json" + destination = tmp_path / "plan.json" + arguments = [ + command, "offline", "--method", "basic", "--dtype", "bfloat16", "--device", device, "--plan-only", + "--plan-config", str(source), "--plan-output", str(destination), + "--plan-free-memory", "96", "96", "--plan-host-memory", "64", "--plan-disk-memory", "1024", + "--plan-batch-size", "1", "--plan-sequence-length", "128", "--plan-generation-tokens", "16", + ] + if device == "auto": + cli.main(arguments) + else: + with pytest.raises(SystemExit) as error: + cli.main(arguments) + assert error.value.code == 2 + report = json.loads(destination.read_text()) + expected = "cuda:0" if device == "cuda" else device + assert report["execution_device"] == expected + if device == "auto": + assert report["status"] == "feasible", report["refusals"] + assert set(report["bytes_by_device"]) == {"cuda:0", "cuda:1"} + else: + assert report["status"] == "refused" + assert set(report["bytes_by_device"]) == {expected} + assert any(reason.startswith(f"load/{expected} shortfall") for reason in report["refusals"]) + + @pytest.mark.parametrize("command", ["obliterate", "abliterate"]) @pytest.mark.parametrize("limit", [None, 64, 1024]) def test_primary_plan_bounds_probe_and_refusal_workloads(monkeypatch, planning_only, command, limit): @@ -143,6 +174,33 @@ def test_concept_baseline_plan_bounds_default_probe(monkeypatch, planning_only): assert planned.call_args.kwargs["sequence_length"] == 256 +@pytest.mark.parametrize("command", ["baseline", "steer"]) +@pytest.mark.parametrize("device", [None, "cuda:1"]) +def test_concept_plan_uses_cpu_default_or_selected_gpu(tmp_path, planning_only, command, device): + source = tmp_path / "config.json" + source.write_text(json.dumps({ + "model_type": "qwen2", "vocab_size": 64, "hidden_size": 32, "intermediate_size": 64, + "num_hidden_layers": 2, "num_attention_heads": 4, "num_key_value_heads": 2, + "max_position_embeddings": 256, "tie_word_embeddings": False, + })) + destination = tmp_path / "plan.json" + options = (["missing/pack", "fixture/model", "--extraction-layer", "0"] if command == "baseline" + else ["fixture/model", "missing.safetensors", "--prompt", "fixture"]) + selection = [] if device is None else ["--device", device, "--plan-free-memory", "0", "8"] + cli.main([ + "concepts", command, *options, "--plan-only", "--output-dir", str(tmp_path / "out"), + "--plan-config", str(source), "--plan-output", str(destination), "--plan-samples", "32", + "--plan-host-memory", "32", "--plan-disk-memory", "64", *selection, + ]) + report = json.loads(destination.read_text()) + assert report["status"] == "feasible", report["refusals"] + assert report["execution_device"] == (device or "cpu") + assert set(report["bytes_by_device"]) == {device or "cpu"} + for rows in report["phases"].values(): + assert "cuda:0" not in rows + assert rows[device or "cpu"]["budget_bytes"] == (8 if device else 32) * 1024**3 + + @pytest.mark.parametrize("neighbour_samples", [None, 0, 1000]) def test_concept_baseline_plan_retains_report_readouts_without_writer_rollback(tmp_path, planning_only, neighbour_samples): source = tmp_path / "config.json" @@ -187,7 +245,7 @@ def test_replication_dry_run_precedes_stage_and_seed(tmp_path, monkeypatch, plan args, model = planned.call_args.args assert model == "fixture/model" and args.plan_only assert args.plan_output == output / "capacity-plan.json" - assert planned.call_args.kwargs == {"dtype": "bfloat16", "batch_size": 8 if stage == "ablate" else 1, + assert planned.call_args.kwargs == {"dtype": "bfloat16", "device": "cuda:0", "batch_size": 8 if stage == "ablate" else 1, "generation_tokens": tokens, "activation_datasets": 7 if stage == "vectors" else 2, "collection_copies": 2 if stage == "vectors" else 0, @@ -232,7 +290,7 @@ def test_appendix_plan_uses_configured_batch_and_longest_completion(tmp_path, mo "--max-new-tokens", "80", "--refusal-eval-max-new-tokens", "128"]) args, model = planned.call_args.args assert model == "fixture/model" and Path(args.plan_output) == evidence - assert planned.call_args.kwargs == {"dtype": "bfloat16", "batch_size": 4, + assert planned.call_args.kwargs == {"dtype": "bfloat16", "device": "cuda:0", "batch_size": 4, "generation_tokens": 128, "concept_edit": True} @@ -247,6 +305,7 @@ def test_recovery_plan_does_not_require_peft_and_declares_training_limit(tmp_pat args, model = planned.call_args.args assert model == "fixture/model" and args.plan_only assert args.plan_output == tmp_path / "out.capacity-plan.json" + assert planned.call_args.kwargs["device"] == "cuda:0" assert planned.call_args.kwargs["sequence_length"] == 512 assert planned.call_args.kwargs["generation_tokens"] == 160 assert planned.call_args.kwargs["concept_edit"] is True diff --git a/tests/test_capacity_planning.py b/tests/test_capacity_planning.py index 3fdb9103..b4d33342 100644 --- a/tests/test_capacity_planning.py +++ b/tests/test_capacity_planning.py @@ -527,6 +527,69 @@ def test_qualification_comparison_retention_refuses_before_model_loading(large_i assert admitted["status"] == "feasible", admitted["refusals"] +@pytest.mark.parametrize("output", ["output_attentions", "output_hidden_states"]) +@pytest.mark.parametrize("split", [False, True]) +def test_forward_estimates_retain_config_enabled_outputs(tiny_inventory, output, split): + inventory = meta_inventory(dict(tiny_inventory["config"], **{output: True})) + budgets = {"cuda:0": 8 * GIB, **({"cuda:1": 8 * GIB} if split else {})} + mapping = {"": "cuda:0"} + if split: + mapping.update({block: "cuda:1" for block in inventory["blocks"][3:]}) + mapping["lm_head"] = "cuda:1" + workload = Workload(batch_size=2, sequence_length=128) + ordinary = plan(tiny_inventory, budgets, device_map=mapping, workload=workload) + retained = plan(inventory, budgets, device_map=mapping, workload=workload) + assert inventory["text_config"][output] is True + for phase in ("baseline", "activations", "verify", "reload"): + for device in budgets: + layers = sum(parameter_device(block, mapping) == device for block in inventory["blocks"]) + per_layer = (2 * 4 * 128**2 * 4 if output == "output_attentions" else 2 * 128 * 32 * 2) + extra = (retained["phases"][phase][device]["components"]["activations"] + - ordinary["phases"][phase][device]["components"]["activations"]) + assert extra >= layers * per_layer + + +@pytest.mark.parametrize("output", ["output_attentions", "output_hidden_states"]) +def test_config_enabled_outputs_can_refuse_an_otherwise_feasible_plan(tiny_inventory, output): + workload = Workload(batch_size=4, sequence_length=2048) + ordinary = plan(tiny_inventory, {"cuda:0": 8 * GIB}, workload=workload) + budget = max(rows["cuda:0"]["peak_bytes"] for rows in ordinary["phases"].values()) + assert plan(tiny_inventory, {"cuda:0": budget}, workload=workload)["status"] == "feasible" + inventory = copy.deepcopy(tiny_inventory) + inventory["text_config"][output] = True + report = plan(inventory, {"cuda:0": budget}, workload=workload) + assert report["status"] == "refused" + assert any(reason.startswith("baseline/cuda:0 shortfall") for reason in report["refusals"]) + + +@pytest.mark.parametrize("staged", [False, True]) +def test_qualification_disk_admission_includes_both_observation_files(staged): + inventory = meta_inventory(read_config("qwen2.5-32b-instruct.json")) + options = dict(batch_size=4, sequence_length=32, generation_tokens=16, samples=3) + budgets = {"cuda:0": 96 * GIB, "cuda:1": 96 * GIB} + disk_budget = (150 if staged else 220) * GIB + ordinary = plan(inventory, budgets, workload=Workload(comparison_prompts=2, **options), + source_staged=staged, host_memory_bytes=256 * GIB, disk_memory_bytes=disk_budget) + assert ordinary["status"] == "feasible", ordinary["refusals"] + workload = Workload(comparison_prompts=100_000, **options) + report = plan(inventory, budgets, workload=workload, source_staged=staged, + host_memory_bytes=256 * GIB, disk_memory_bytes=disk_budget) + assert report["status"] == "refused" + assert all(row["headroom_bytes"] >= 0 for rows in report["phases"].values() + for device, row in rows.items() if device != "disk") + assert any(reason.startswith("save/disk shortfall") for reason in report["refusals"]) + per_set = 100_000 * (inventory["text_config"]["vocab_size"] * 4 + 48 * 8) + observation_bytes = 4 * per_set + 4 * 64 * 5120 * 4 + for phase, rows in report["phases"].items(): + if phase != "reload": + assert rows["disk"]["components"]["qualification_observations"] == observation_bytes + # Reload observes free space after the checkpoint and observation files exist. + assert "qualification_observations" not in report["phases"]["reload"]["disk"]["components"] + admitted = plan(inventory, budgets, workload=workload, source_staged=staged, + host_memory_bytes=256 * GIB, disk_memory_bytes=512 * GIB) + assert admitted["status"] == "feasible", admitted["refusals"] + + @pytest.mark.parametrize("dtype", ["bfloat16", "float32"]) def test_concept_concatenations_copy_rows_without_sequence_backing(tiny_inventory, dtype): inventory = meta_inventory(tiny_inventory["config"], dtype=dtype) @@ -1055,6 +1118,69 @@ def test_plan_rejects_invalid_utilization(tiny_inventory, monkeypatch, utilizati maybe_plan(args, "offline", sequence_length=128) +@pytest.mark.parametrize("device,options,message", [ + ("cuda:2", [], "visible-order budget for cuda:2"), + ("mps", [], "no capacity contract for execution device"), + ("cuda:0", ["--plan-offload", "cpu"], "Explicit execution devices"), +]) +def test_plan_refuses_incompatible_execution_placement(tiny_inventory, monkeypatch, device, options, message): + monkeypatch.setattr("obliteratus.capacity_planning.meta_inventory", lambda *args: tiny_inventory) + parser = argparse.ArgumentParser() + add_capacity_arguments(parser) + args = parser.parse_args([ + "--plan-only", "--plan-config", str(CONFIGS / "qwen2.5-72b-instruct.json"), + "--plan-free-memory", "8", "8", "--plan-host-memory", "64", "--plan-disk-memory", "64", + "--plan-samples", "32", *options, + ]) + args.device = device + with pytest.raises(ValueError, match=message): + maybe_plan(args, "offline", sequence_length=128) + + +def test_explicit_execution_device_rejects_conflicting_map(tiny_inventory, monkeypatch): + from scripts import gpu_qualification as driver + + monkeypatch.setattr("obliteratus.capacity_planning.meta_inventory", lambda *args: tiny_inventory) + args = driver.parser().parse_args([ + "--output", "unused", "--plan-only", "--plan-config", str(CONFIGS / "qwen2.5-72b-instruct.json"), + "--plan-free-memory", "8", "8", "--plan-host-memory", "64", "--plan-disk-memory", "64", + ]) + args.device_map = {"": "cuda:0", "model.layers.0": "cpu"} + with pytest.raises(ValueError, match="map conflicts with the requested execution device"): + maybe_plan(args, "offline", device="cuda:0", sequence_length=128) + + +@pytest.mark.parametrize("budgets", [[8], [8, 8, 8]]) +def test_driver_dry_run_requires_requested_gpu_count(tmp_path, monkeypatch, budgets): + from scripts import gpu_qualification as driver + + monkeypatch.setattr(driver, "supervise", Mock(side_effect=AssertionError("dry-run launched a worker"))) + with pytest.raises(ValueError, match="exactly --devices"): + driver.main([ + "--output", str(tmp_path / "unused"), "--plan-only", "--devices", "2", + "--plan-free-memory", *map(str, budgets), + ]) + + +@pytest.mark.parametrize("offload", ["none", "cpu", "disk"]) +def test_driver_rehearsal_dry_run_uses_host_budget(tmp_path, tiny_inventory, monkeypatch, offload): + from scripts import gpu_qualification as driver + + monkeypatch.setattr("obliteratus.capacity_planning.meta_inventory", lambda *args: tiny_inventory) + monkeypatch.setattr(driver, "supervise", Mock(side_effect=AssertionError("dry-run launched a worker"))) + destination = tmp_path / "plan.json" + assert driver.main([ + "--output", str(tmp_path / "unused"), "--plan-only", "--mode", "rehearsal", "--devices", "3", + "--offload", offload, + "--plan-config", str(CONFIGS / "qwen2.5-72b-instruct.json"), "--plan-output", str(destination), + "--plan-host-memory", "64", "--plan-disk-memory", "64", + ]) == 0 + report = json.loads(destination.read_text()) + assert report["execution_device"] == "cpu" + assert set(report["bytes_by_device"]) == ({"cpu", "disk"} if offload == "disk" else {"cpu"}) + assert all(set(rows) == {"cpu", "disk"} for rows in report["phases"].values()) + + @pytest.mark.parametrize("samples", [None, 64]) def test_driver_plan_counts_selected_workload(tmp_path, tiny_inventory, monkeypatch, samples): from scripts import gpu_qualification as driver diff --git a/tests/test_gpu_qualification_runtime.py b/tests/test_gpu_qualification_runtime.py index 9ba25233..6fbe784a 100644 --- a/tests/test_gpu_qualification_runtime.py +++ b/tests/test_gpu_qualification_runtime.py @@ -515,11 +515,15 @@ def test_frozen_disk_admission_uses_remaining_phase_demand( gib = 1024**3 weights = 65_527_752_704 offload = offload_gib * gib - disk_load = 2 * weights + offload + gib + observations = 16_384 + disk_load = 2 * weights + offload + observations + gib disk_reload = offload + gib completed = weights if reference else 0 - required = disk_load - completed if phase == "load" else disk_reload - remaining = 140 * gib - completed - (weights if phase == "reload" else 0) + completed_observations = observations // 2 if reference else 0 + if reference: + (tmp_path / "reference-observations.safetensors").write_bytes(b"x" * completed_observations) + required = disk_load - completed - completed_observations if phase == "load" else disk_reload + remaining = 140 * gib - completed - completed_observations - (weights + observations if phase == "reload" else 0) if lost_headroom: remaining = required - 1 monkeypatch.setattr(runtime.shutil, "disk_usage", lambda path: SimpleNamespace(free=remaining)) @@ -544,7 +548,9 @@ def test_frozen_disk_admission_uses_remaining_phase_demand( "completed_reference_export_bytes": completed + 4096 if reference else 0, "capacity_plan": {"device_map": mapping, "total_weight_bytes": weights, "phases": { "load": {"cpu": {"peak_bytes": 64 * gib}, "disk": {"peak_bytes": disk_load}}, - "save": {"cpu": {"peak_bytes": 96 * gib}, "disk": {"peak_bytes": disk_load}}, + "save": {"cpu": {"peak_bytes": 96 * gib}, "disk": { + "peak_bytes": disk_load, "components": {"qualification_observations": observations}, + }}, "reload": {"cpu": {"peak_bytes": 32 * gib}, "disk": {"peak_bytes": disk_reload}}, }}, }