From f2da875345673945de2f477538ff2b75dbcdccbf Mon Sep 17 00:00:00 2001 From: Joseph Magly <1159087+jmagly@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:28:48 -0500 Subject: [PATCH 1/2] feat(qwen38): add a cv_auc concept-arm variant and record the loadpath-333 concept variant Adds --loadpath-concept-layer-select {all,cv_auc} so the loadpath-333 concept arm can rerun with data-driven layer selection, alone or with --loadpath-causal-control (same recipe on the CausalLM path). Stage and edit evidence record the variant (concept_variant) and the selected layers; quality gates keep reporting without vetoing edits. The default 'all' keeps the original recipe and manifest. CPU tests cover the options with stubbed model work; the docs add the A100 command lines. Fixes #383 Refs #333 --- CHANGELOG.md | 7 ++ docs/QWEN38_A100_CAMPAIGN.md | 72 +++++++++++++- scripts/qwen38_a100_campaign.py | 9 +- scripts/qwen38_campaign_arms.py | 40 ++++++++ scripts/qwen38_campaign_probes.py | 23 ++++- tests/test_qwen38_campaign_control.py | 129 ++++++++++++++++++++++++++ 6 files changed, 273 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 51f7e78b..1ebb8d78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,13 @@ checkpoint export, receipts, and versioned recipe composition. The original Inkling-2-Mini result was confounded by a compliance prefill and is not treated as validation. See [Vocabulary-row edits](docs/VOCABULARY_ROW_EDITS.md). +- Added `--loadpath-concept-layer-select {all,cv_auc}` to the Qwen3.8 campaign + (#383). `cv_auc` reruns the `loadpath-333` concept arm with data-driven layer + selection; with `--loadpath-causal-control` both loaders share that recipe. + `loadpath-333/result.json` and each concept edit record the variant that ran + (`concept_variant`) and the selected layers. Quality gates still report + without vetoing edits. The default `all` keeps the original recipe and manifest. + See [Qwen3.8 campaign](docs/QWEN38_A100_CAMPAIGN.md#383-separate-the-concept-recipe-from-the-load-path). ### Changed diff --git a/docs/QWEN38_A100_CAMPAIGN.md b/docs/QWEN38_A100_CAMPAIGN.md index 44a5cb41..f6b8bd91 100644 --- a/docs/QWEN38_A100_CAMPAIGN.md +++ b/docs/QWEN38_A100_CAMPAIGN.md @@ -514,8 +514,8 @@ first invocation with a **fresh campaign root**, and repeat it on every resume: The default still edits `refusal` and `concept` through ImageTextToText. This option adds `concept-causal`, using CausalLM with the **same** pinned S2 prompts, controls, seed 0, `basic` pipeline method and `diff_means` recipe with -`layer_select: {strategy: preset, preset: all}`. It does not switch to `cv_auc` -or change quality thresholds. The extra edit and reload require additional GPU +`layer_select: {strategy: preset, preset: all}`. By itself it does not switch to +`cv_auc` (see the #383 section below) or change quality thresholds. The extra edit and reload require additional GPU work beyond the default stage allowance; this control has no measured runtime allowance yet. @@ -557,6 +557,74 @@ quality failures do not establish edited-logit parity, path independence, or operator decision on the text-only option; CPU tests and small-model runs cannot supply that evidence. +### #383: separate the concept recipe from the load path + +The original `loadpath-333` concept arm excised a weak pilot direction at every +layer (`preset: all`), so its failure cannot be attributed to the composite load +path. Two locked options separate the factors; use either or both: + +| Option | Changes | Isolates | +|---|---|---| +| `--loadpath-causal-control` | Adds `concept-causal`: the same recipe and inputs on CausalLM | Load path | +| `--loadpath-concept-layer-select cv_auc` | Concept arms pick their extraction layer by held-out `cv_auc` (5 folds; fewer only when a rehearsal set is smaller) instead of all layers | Recipe (layer selection) | + +`--loadpath-concept-layer-select all` is the default and reproduces the #383 +recipe; it adds nothing to the manifest. `cv_auc` is recorded as +`options.loadpath_concept_layer_select` and in `protocol_rules.composite_concept`. +With both options, both concept arms share the `cv_auc` recipe and the matched +control still checks that their inputs are identical. Each option needs a +**fresh campaign root** and must be repeated on every resume; changing either +on a locked root is rejected. + +Exact A100 command lines (one fresh root per variant): + +```bash +cd /path/to/OBLITERATUS +# 1. Rehearse the options end to end on the rented GPU with the small stand-in. +.venv/bin/python scripts/qwen38_a100_campaign.py \ + --root /mnt/qwen38-383-rehearsal --stages loadpath-333 --dry-run \ + --model-override Qwen/Qwen3.5-0.8B --max-prompts 2 --budget-hours 2 \ + --pain-pin /mnt/pain-axis-pin \ + --loadpath-causal-control --loadpath-concept-layer-select cv_auc + +# 2. Load-path control: the original all-layer recipe on both loaders. +.venv/bin/python scripts/qwen38_a100_campaign.py \ + --root /mnt/qwen38-383-preset-all-causal --stages loadpath-333 \ + --pain-pin /mnt/pain-axis-pin --loadpath-causal-control + +# 3. Recipe control: data-driven layer selection on both loaders. +.venv/bin/python scripts/qwen38_a100_campaign.py \ + --root /mnt/qwen38-383-cv-auc-causal --stages loadpath-333 \ + --pain-pin /mnt/pain-axis-pin --loadpath-causal-control \ + --loadpath-concept-layer-select cv_auc +``` + +Add `--resume` with otherwise identical arguments after an interruption. Run 2 +first if only one paid window is available: it answers whether the failure +follows the load path. Run 3 shows whether a data-driven recipe passes on either +path. Each variant with the causal control adds one concept edit and one reload +beyond the default `loadpath-333` allowance, which has no measured runtime yet. + +Before renting, the CPU lane exercises the options end to end with stubbed model +work (`loadpath` → `_concept_target` → `_edit` → evidence), real `cv_auc` +extraction at rehearsal counts, and manifest locking: + +```bash +nix run .#test -- -q tests/test_qwen38_campaign_control.py +``` + +Every run records which variant executed. `loadpath-333/result.json` and each +concept `*-edit.json` carry `concept_variant` (schema version 1): `layer_select`, +`causal_control`, `concept_arms`, `label` (`preset-all`, `cv-auc`, and either with +`+causal-control`), `matches_original_383_recipe` and `separates` (`load_path`, +`layer_selection`). Each concept edit also records `concept_layers` (extraction +and intervention layers and per-layer mean `cv_auc`), and its `edit_provenance` +recipe includes the exact `layer_select` with its fold count. The report embeds +the stage result. Quality gates are still measured and reported; a failure +contributes **FAIL** to the stage verdict but never vetoes or reverts the +operator's edit. A `cv_auc` pass is recipe evidence and does not by itself +establish path independence; compare it with the causal arm. + Pain Axis extracts fresh S2, S1, and control vectors, runs separate S1, S2, and random-sentence control batteries, tests D4 refusal-projection protection, and evaluates the #346 trained repair. diff --git a/scripts/qwen38_a100_campaign.py b/scripts/qwen38_a100_campaign.py index 356c84b8..fe9d1505 100644 --- a/scripts/qwen38_a100_campaign.py +++ b/scripts/qwen38_a100_campaign.py @@ -503,7 +503,9 @@ def preflight(request, output_dir): "pain_pin": {"commit": pin_commit, "files": pin_files}, "pain_inputs": pain_inputs, "protocol_rules": {"pain_layers": "floor(n_layers/3), floor(n_layers/2)", "pain_battery_arms": ["s1", "s2", "random_set"], - "composite_concept": "pinned S2 pain/control categories, difference of means, all layers", + "composite_concept": "pinned S2 pain/control categories, difference of means, " + ( + "cv_auc layer selection" if options.get("loadpath_concept_layer_select") == "cv_auc" + else "all layers"), "loadpath_parity": "all input-token logits on four fixed text prompts", "pain_replication": "not_applicable; no shipped Qwen3.8 vectors", "dtype": "bfloat16", "device": "cuda", "evaluation_seed": 0, @@ -1452,6 +1454,8 @@ def parse_args(argv=None): parser.add_argument("--keep-checkpoints", action="store_true") parser.add_argument("--loadpath-causal-control", action="store_true", help="also edit CausalLM with the composite concept arm's exact recipe and inputs") + parser.add_argument("--loadpath-concept-layer-select", choices=("all", "cv_auc"), default="all", + help="concept arm layer selection: all (the #383 recipe, default) or data-driven cv_auc") parser.add_argument("--rerun-seeds", default="0,1,2", help="distinct rerun seeds (default: 0,1,2)") parser.add_argument("--pain-pin", type=Path, default=REPO.parent / "pain-axis-pin") parser.add_argument("--pain-prompts", type=Path) @@ -1560,6 +1564,9 @@ def campaign(args): if args.loadpath_causal_control: # Absence retains the legacy manifest shape and two composite edit arms. options["loadpath_causal_control"] = True + if args.loadpath_concept_layer_select != "all": + # Recorded only for the opt-in variant, so default manifests resume unchanged. + options["loadpath_concept_layer_select"] = args.loadpath_concept_layer_select if args.symlink_inputs is not None: # Check the directory as given, before anything resolves links away. given = args.symlink_inputs.expanduser() diff --git a/scripts/qwen38_campaign_arms.py b/scripts/qwen38_campaign_arms.py index 009ceec2..798779e0 100644 --- a/scripts/qwen38_campaign_arms.py +++ b/scripts/qwen38_campaign_arms.py @@ -4,6 +4,9 @@ from __future__ import annotations EDIT_LOADERS = {"refusal": "composite", "concept": "composite", "concept-causal": "causal"} +# The #383 failure used every layer; ``cv_auc`` is the opt-in data-driven variant. +CONCEPT_LAYER_SELECTS = ("all", "cv_auc") +CV_AUC_FOLDS = 5 def selected_arms(options): @@ -22,6 +25,43 @@ def reload_loaders(arm): return ("causal",) if edit_loader(arm) == "causal" else ("causal", "composite") +def concept_layer_select_name(options): + name = options.get("loadpath_concept_layer_select", "all") + if name not in CONCEPT_LAYER_SELECTS: + raise ValueError(f"unknown load-path concept layer selection: {name!r}") + return name + + +def concept_layer_select(options, set_sizes): + """Return the concept recipe's ``layer_select`` for the locked campaign variant. + + ``cv_auc`` uses five folds, or fewer when a tiny rehearsal set is smaller; + the fold count is part of the recipe and therefore of every arm's provenance. + """ + if concept_layer_select_name(options) == "all": + return {"strategy": "preset", "preset": "all"} + folds = min(CV_AUC_FOLDS, *set_sizes) + if folds < 2: + raise ValueError("cv_auc concept layer selection needs at least two prompts in every set") + return {"strategy": "cv_auc", "folds": folds} + + +def concept_variant(options): + """Describe which concept-arm variant this locked run executes (#383).""" + layer_select = concept_layer_select_name(options) + causal = bool(options.get("loadpath_causal_control")) + return { + "schema_version": 1, + "layer_select": layer_select, + "causal_control": causal, + "concept_arms": ["concept", "concept-causal"] if causal else ["concept"], + "label": ("preset-all" if layer_select == "all" else "cv-auc") + ("+causal-control" if causal else ""), + "matches_original_383_recipe": layer_select == "all", + "separates": [factor for factor, selected in ( + ("load_path", causal), ("layer_selection", layer_select == "cv_auc")) if selected], + } + + def edit_provenance(arm, target): return { "schema_version": 1, "arm": arm, "edit_loader": edit_loader(arm), "seed": 0, diff --git a/scripts/qwen38_campaign_probes.py b/scripts/qwen38_campaign_probes.py index 4d77e787..3439c1ae 100644 --- a/scripts/qwen38_campaign_probes.py +++ b/scripts/qwen38_campaign_probes.py @@ -258,7 +258,7 @@ def _claim_checkpoint(root, label): def loadpath(manifest: dict, root: Path): """Collect #333 evidence, loading only one full model in each subprocess.""" - from scripts.qwen38_campaign_arms import control_evidence, reload_loaders, selected_arms + from scripts.qwen38_campaign_arms import concept_variant, control_evidence, reload_loaders, selected_arms root = Path(root) options = _options(manifest) @@ -277,6 +277,7 @@ def loadpath(manifest: dict, root: Path): result = { "dry_run": bool(options.get("dry_run")), "pristine": {"causal": causal, "composite": composite}, "logit_parity": parity, "arms": arms, "concept_control": control_evidence(arms, options), + "concept_variant": concept_variant(options), "verdict": "PASS" if parity["pass"] and all( probe["gsq"]["pass"] and probe["memory_admission"] == "PASS" for probe in (causal, composite)) and all( @@ -503,6 +504,7 @@ def _pipeline(model, tokenizer, manifest, root, *, concept=None): def _concept_target(manifest): from obliteratus.concepts.target import ConceptTarget, ExtractionRecipe + from scripts.qwen38_campaign_arms import concept_layer_select source = Path(_options(manifest)["pain_pin"]) / "datasets/3.1_pain_and_control_datasets.json" rows = json.loads(source.read_text())["datasets"]["S2_1P"]["sentences"] @@ -511,19 +513,21 @@ def _concept_target(manifest): for name, category in (("fear", "B"), ("negative_emotion", "C1"), ("negative_context", "C2"), ("neutral", "D"), ("positive", "E"))} controls = {name: prompts[:_limit(manifest, len(prompts))] for name, prompts in controls.items()} + positive = positive[:_limit(manifest, len(positive))] + layer_select = concept_layer_select(_options(manifest), [len(positive)] + [len(rows) for rows in controls.values()]) return ConceptTarget(id="user/campaign-pain-pilot", tier="user", - positive=positive[:_limit(manifest, len(positive))], controls=controls, + positive=positive, controls=controls, neighbours={name: controls[name] for name in ("fear", "negative_emotion")}, recipe=ExtractionRecipe(method="diff_means", n_directions=1, collateral_margin=_gates(manifest)["collateral_margin"], - layer_select={"strategy": "preset", "preset": "all"}), + layer_select=layer_select), caveats=["Fresh pinned S2 concept extraction; no shipped Qwen3.8 reference direction."]) def _edit(manifest, root, arm): from dataclasses import asdict from obliteratus.checkpoint_evaluation import validate_evaluation_count - from scripts.qwen38_campaign_arms import edit_loader, edit_provenance + from scripts.qwen38_campaign_arms import concept_variant, edit_loader, edit_provenance loader = edit_loader(arm) target = _concept_target(manifest) if arm in ("concept", "concept-causal") else None @@ -573,6 +577,17 @@ def _edit(manifest, root, arm): "operator_override": REASON, "checkpoint": str(root / "checkpoints/active"), "gsq": _gsq(root / "checkpoints/active", model), "validation": pipeline.validation_report} + if target is not None: + record["concept_variant"] = concept_variant(_options(manifest)) + # Selected layers distinguish an all-layer excision from a cv_auc pick. + direction = getattr(pipeline, "concept_direction", None) + record["concept_layers"] = { + "extraction": [int(layer) for layer in getattr(direction, "extraction_layers", None) or []], + "intervention": [int(layer) for layer in getattr(direction, "intervention_layers", None) or []], + "cv_auc_mean": {str(layer): float(sum(scores)) / len(scores) + for layer, scores in (getattr(direction, "cv_scores", None) or {}).items() + if scores}, + } if pipeline.evaluation_report is not None: record["concept_battery"] = asdict(pipeline.evaluation_report) _write(root / "loadpath-333" / f"{arm}-edit.json", record) diff --git a/tests/test_qwen38_campaign_control.py b/tests/test_qwen38_campaign_control.py index bdc60e74..6c589365 100644 --- a/tests/test_qwen38_campaign_control.py +++ b/tests/test_qwen38_campaign_control.py @@ -184,3 +184,132 @@ def test_cli_locks_only_explicit_control_and_rejects_option_changes(tmp_path, mo with pytest.raises(campaign.CampaignError, match="locked inputs changed: options"): campaign.campaign(campaign.parse_args([*changed, "--resume"])) assert (root / "run-manifest.json").read_bytes() == original + + +# --- #383: separate the concept recipe from the load path ------------------------------- + + +@pytest.mark.parametrize("layer_select,causal,label,separates", [ + ("all", False, "preset-all", []), + ("all", True, "preset-all+causal-control", ["load_path"]), + ("cv_auc", False, "cv-auc", ["layer_selection"]), + ("cv_auc", True, "cv-auc+causal-control", ["load_path", "layer_selection"]), +]) +def test_dry_run_loadpath_records_concept_variant_end_to_end( + tmp_path, monkeypatch, manifest, edit_stub, layer_select, causal, label, separates, +): + """Drive loadpath -> real _edit/_concept_target with model work stubbed on CPU.""" + options = manifest["locked_inputs"]["options"] + options["loadpath_causal_control"] = causal + if layer_select != "all": + options["loadpath_concept_layer_select"] = layer_select + + def run(kind, step_manifest, root, *, arm=None, auto_class=None): + if kind == "loadpath-pristine": + return {"peak_gpu_memory_bytes": 123, "vision_parameter_bytes": 12, + "memory_admission": "PASS", "gsq": {"pass": True}} + if kind == "loadpath-parity": + return {"pass": True} + if kind == "loadpath-edit": + return probes._edit(step_manifest, root, arm) + return {"pass": True} + + monkeypatch.setattr(probes, "_run_step", run) + result = probes.loadpath(manifest, tmp_path) + variant = result["concept_variant"] + assert variant["label"] == label and variant["separates"] == separates + assert variant["layer_select"] == layer_select and variant["causal_control"] is causal + assert variant["matches_original_383_recipe"] is (layer_select == "all") + concept_arms = ["concept", "concept-causal"] if causal else ["concept"] + assert variant["concept_arms"] == concept_arms + expected = ({"strategy": "preset", "preset": "all"} if layer_select == "all" + else {"strategy": "cv_auc", "folds": 2}) # dry-run sets hold two prompts + for arm in concept_arms: + record = campaign.read_json(tmp_path / "loadpath-333" / f"{arm}-edit.json") + assert record["concept_variant"] == variant + assert record["edit_provenance"]["recipe"]["layer_select"] == expected + # Quality gates keep reporting failures without vetoing the operator's edit. + assert record["quality_gate_pass"] is False and record["operator_override"] == probes.REASON + assert (tmp_path / "loadpath-333" / f"loadpath-{arm}-checkpoint-provenance.json").is_file() + assert "concept_variant" not in result["arms"]["refusal"]["edit"] + assert result["verdict"] == "FAIL" + assert result["concept_control"]["mode"] == ("matched_recipe_causal" if causal else "not_requested") + if causal: + assert result["concept_control"]["matched_inputs"] is True + assert campaign.read_json(tmp_path / "loadpath-333/result.json") == result + + +def test_cv_auc_recipe_uses_five_folds_on_full_sets_and_rejects_singletons(manifest): + options = {"loadpath_concept_layer_select": "cv_auc"} + assert arms.concept_layer_select(options, [40, 20, 20]) == {"strategy": "cv_auc", "folds": 5} + assert arms.concept_layer_select(options, [40, 3, 20]) == {"strategy": "cv_auc", "folds": 3} + assert arms.concept_layer_select({}, [1]) == {"strategy": "preset", "preset": "all"} + with pytest.raises(ValueError, match="at least two prompts"): + arms.concept_layer_select(options, [40, 1]) + with pytest.raises(ValueError, match="unknown load-path concept layer selection"): + arms.concept_variant({"loadpath_concept_layer_select": "knee"}) + manifest["locked_inputs"]["options"].update(max_prompts=None, dry_run=False, + loadpath_concept_layer_select="cv_auc") + target = probes._concept_target(manifest) + assert target.recipe.layer_select == {"strategy": "cv_auc", "folds": 3} # fixture sets hold three + + +def test_cv_auc_dry_run_recipe_selects_one_layer_with_real_extraction(manifest): + torch = pytest.importorskip("torch") + from obliteratus.concepts.extraction import extract_directions + + manifest["locked_inputs"]["options"]["loadpath_concept_layer_select"] = "cv_auc" + target = probes._concept_target(manifest) + generator = torch.Generator().manual_seed(0) + layers = range(4) + + def cache(count, shift): + return {layer: torch.randn(count, 8, generator=generator) + shift * (layer == 2) + for layer in layers} + + positive = cache(len(target.positive), 4.0) + controls = {name: cache(len(rows), 0.0) for name, rows in target.controls.items()} + direction = extract_directions(positive, controls, target.recipe, seed=0, model_id="fixture") + assert direction.extraction_layers == [2] and direction.intervention_layers == [2] + assert sorted(direction.cv_scores) == list(layers) + assert all(len(scores) == 2 for scores in direction.cv_scores.values()) + + +def test_cli_locks_concept_layer_select_variant_and_rejects_changes(tmp_path, monkeypatch): + root = tmp_path / "run" + base = ["--root", str(root), "--stages", "preflight", "--loadpath-causal-control"] + argv = [*base, "--loadpath-concept-layer-select", "cv_auc"] + + def preflight(_root, _name, _command, output, _inputs, **_kwargs): + request = campaign.read_json(root / "preflight-request.json") + campaign.write_json(output / "result.json", {"locked_inputs": {"options": request["options"]}}) + + monkeypatch.setattr(campaign, "run_subprocess", preflight) + assert campaign.parse_args(base).loadpath_concept_layer_select == "all" + campaign.campaign(campaign.parse_args(argv)) + original = (root / "run-manifest.json").read_bytes() + options = campaign.read_json(root / "run-manifest.json")["locked_inputs"]["options"] + assert options["loadpath_concept_layer_select"] == "cv_auc" + assert options["loadpath_causal_control"] is True + campaign.campaign(campaign.parse_args([*argv, "--resume"])) + assert (root / "run-manifest.json").read_bytes() == original + for changed in (base, [*base, "--loadpath-concept-layer-select", "all"]): + with pytest.raises(campaign.CampaignError, match="locked inputs changed: options"): + campaign.campaign(campaign.parse_args([*changed, "--resume"])) + assert (root / "run-manifest.json").read_bytes() == original + with pytest.raises(SystemExit): + campaign.parse_args([*base, "--loadpath-concept-layer-select", "knee"]) + + +def test_default_layer_select_adds_no_manifest_option(tmp_path, monkeypatch): + root = tmp_path / "run" + + def preflight(_root, _name, _command, output, _inputs, **_kwargs): + request = campaign.read_json(root / "preflight-request.json") + campaign.write_json(output / "result.json", {"locked_inputs": {"options": request["options"]}}) + + monkeypatch.setattr(campaign, "run_subprocess", preflight) + campaign.campaign(campaign.parse_args(["--root", str(root), "--stages", "preflight", + "--loadpath-concept-layer-select", "all"])) + options = campaign.read_json(root / "run-manifest.json")["locked_inputs"]["options"] + assert "loadpath_concept_layer_select" not in options From 1b5a54bcab69d8916616629f2f6514556e06a0a5 Mon Sep 17 00:00:00 2001 From: Joseph Magly <1159087+jmagly@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:50:27 -0500 Subject: [PATCH 2/2] fix(qwen38-campaign): reject impossible cv_auc runs before any GPU stage cv_auc concept layer selection needs at least two prompts in every set, but the fold check ran in _concept_target, after the pristine probes, parity, the refusal edit and both refusal reloads. A locked prompt cap then needed a fresh root to recover. Share the minimum as CV_AUC_MIN_PROMPTS and the capped pinned sets as _concept_prompts. parse_args rejects an explicit --max-prompts below the minimum. campaign() checks the effective pinned set sizes before the run lock, inputs and preflight, so fresh and resumed roots are refused unchanged. loadpath() repeats the check before its first pristine probe. --- scripts/qwen38_a100_campaign.py | 15 ++++++++ scripts/qwen38_campaign_arms.py | 7 ++-- scripts/qwen38_campaign_probes.py | 38 +++++++++++++++----- tests/test_qwen38_campaign_control.py | 50 +++++++++++++++++++++++++-- 4 files changed, 96 insertions(+), 14 deletions(-) diff --git a/scripts/qwen38_a100_campaign.py b/scripts/qwen38_a100_campaign.py index fe9d1505..be8a227c 100644 --- a/scripts/qwen38_a100_campaign.py +++ b/scripts/qwen38_a100_campaign.py @@ -1476,6 +1476,11 @@ def parse_args(argv=None): args.root = args.root.expanduser().resolve() if args.max_prompts is not None and args.max_prompts < 1: parser.error("--max-prompts must be positive") + from scripts.qwen38_campaign_arms import CV_AUC_MIN_PROMPTS + + if (args.loadpath_concept_layer_select == "cv_auc" and args.max_prompts is not None + and args.max_prompts < CV_AUC_MIN_PROMPTS): + parser.error(f"--loadpath-concept-layer-select cv_auc needs --max-prompts of at least {CV_AUC_MIN_PROMPTS}") if not math.isfinite(args.budget_hours) or args.budget_hours <= 0: parser.error("--budget-hours must be finite and positive") if not math.isfinite(args.min_vram_gb) or args.min_vram_gb <= 0: @@ -1537,6 +1542,16 @@ def campaign(args): args.model_override = "Qwen/Qwen3.5-0.8B" if args.dry_run and args.max_prompts is None: args.max_prompts = 2 + if args.loadpath_concept_layer_select == "cv_auc": + # Check the capped pinned sets before any stage worker, so a locked root never holds an impossible recipe. + from scripts.qwen38_campaign_probes import concept_layer_select_for + + try: + concept_layer_select_for({"pain_pin": str(args.pain_pin.expanduser().resolve()), + "max_prompts": args.max_prompts, "dry_run": args.dry_run, + "loadpath_concept_layer_select": "cv_auc"}) + except (OSError, KeyError, ValueError) as error: + raise CampaignError(f"--loadpath-concept-layer-select cv_auc cannot run: {error}") from error gates = {**GATES, **(read_json(args.gates) if args.gates else {})} if set(gates) != set(GATES) or any(isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or v < 0 for v in gates.values()): diff --git a/scripts/qwen38_campaign_arms.py b/scripts/qwen38_campaign_arms.py index 798779e0..654f312f 100644 --- a/scripts/qwen38_campaign_arms.py +++ b/scripts/qwen38_campaign_arms.py @@ -7,6 +7,8 @@ EDIT_LOADERS = {"refusal": "composite", "concept": "composite", "concept-causal" # The #383 failure used every layer; ``cv_auc`` is the opt-in data-driven variant. CONCEPT_LAYER_SELECTS = ("all", "cv_auc") CV_AUC_FOLDS = 5 +# Every fold split needs a held-out prompt and a training prompt in each set. +CV_AUC_MIN_PROMPTS = 2 def selected_arms(options): @@ -41,8 +43,9 @@ def concept_layer_select(options, set_sizes): if concept_layer_select_name(options) == "all": return {"strategy": "preset", "preset": "all"} folds = min(CV_AUC_FOLDS, *set_sizes) - if folds < 2: - raise ValueError("cv_auc concept layer selection needs at least two prompts in every set") + if folds < CV_AUC_MIN_PROMPTS: + raise ValueError(f"cv_auc concept layer selection needs at least {CV_AUC_MIN_PROMPTS} prompts in every set " + f"(effective set sizes: {list(set_sizes)})") return {"strategy": "cv_auc", "folds": folds} diff --git a/scripts/qwen38_campaign_probes.py b/scripts/qwen38_campaign_probes.py index 3439c1ae..52dbea78 100644 --- a/scripts/qwen38_campaign_probes.py +++ b/scripts/qwen38_campaign_probes.py @@ -89,7 +89,10 @@ def _fetch(root): def _limit(manifest, default): - options = _options(manifest) + return _options_limit(_options(manifest), default) + + +def _options_limit(options, default): limit = options.get("max_prompts") if limit is None: return min(default, 2) if options.get("dry_run") else default @@ -262,6 +265,8 @@ def loadpath(manifest: dict, root: Path): root = Path(root) options = _options(manifest) + # An impossible concept recipe must fail here, not after the pristine probes and refusal arm. + concept_layer_select_for(options) out = root / "loadpath-333" out.mkdir(parents=True, exist_ok=True) causal = _run_step("loadpath-pristine", manifest, root, auto_class="causal") @@ -502,19 +507,34 @@ def _pipeline(model, tokenizer, manifest, root, *, concept=None): return pipeline -def _concept_target(manifest): - from obliteratus.concepts.target import ConceptTarget, ExtractionRecipe - from scripts.qwen38_campaign_arms import concept_layer_select - - source = Path(_options(manifest)["pain_pin"]) / "datasets/3.1_pain_and_control_datasets.json" +def _concept_prompts(options): + """The pinned S2 concept sets after the locked prompt cap, as every concept arm uses them.""" + source = Path(options["pain_pin"]) / "datasets/3.1_pain_and_control_datasets.json" rows = json.loads(source.read_text())["datasets"]["S2_1P"]["sentences"] positive = [row["prompt"] for row in rows if row["category"] in {"A1", "A2", "A3", "A4", "A5"}] controls = {name: [row["prompt"] for row in rows if row["category"] == category] for name, category in (("fear", "B"), ("negative_emotion", "C1"), ("negative_context", "C2"), ("neutral", "D"), ("positive", "E"))} - controls = {name: prompts[:_limit(manifest, len(prompts))] for name, prompts in controls.items()} - positive = positive[:_limit(manifest, len(positive))] - layer_select = concept_layer_select(_options(manifest), [len(positive)] + [len(rows) for rows in controls.values()]) + controls = {name: prompts[:_options_limit(options, len(prompts))] for name, prompts in controls.items()} + return positive[:_options_limit(options, len(positive))], controls + + +def concept_layer_select_for(options): + """Resolve the concept ``layer_select``; raises ``ValueError`` before GPU work when it cannot run.""" + from scripts.qwen38_campaign_arms import concept_layer_select, concept_layer_select_name + + if concept_layer_select_name(options) == "all": + # The #383 recipe needs no pinned set sizes, so the default path reads nothing. + return concept_layer_select(options, []) + positive, controls = _concept_prompts(options) + return concept_layer_select(options, [len(positive)] + [len(rows) for rows in controls.values()]) + + +def _concept_target(manifest): + from obliteratus.concepts.target import ConceptTarget, ExtractionRecipe + + positive, controls = _concept_prompts(_options(manifest)) + layer_select = concept_layer_select_for(_options(manifest)) return ConceptTarget(id="user/campaign-pain-pilot", tier="user", positive=positive, controls=controls, neighbours={name: controls[name] for name in ("fear", "negative_emotion")}, diff --git a/tests/test_qwen38_campaign_control.py b/tests/test_qwen38_campaign_control.py index 6c589365..98c64bfb 100644 --- a/tests/test_qwen38_campaign_control.py +++ b/tests/test_qwen38_campaign_control.py @@ -244,7 +244,7 @@ def test_cv_auc_recipe_uses_five_folds_on_full_sets_and_rejects_singletons(manif assert arms.concept_layer_select(options, [40, 20, 20]) == {"strategy": "cv_auc", "folds": 5} assert arms.concept_layer_select(options, [40, 3, 20]) == {"strategy": "cv_auc", "folds": 3} assert arms.concept_layer_select({}, [1]) == {"strategy": "preset", "preset": "all"} - with pytest.raises(ValueError, match="at least two prompts"): + with pytest.raises(ValueError, match=f"at least {arms.CV_AUC_MIN_PROMPTS} prompts"): arms.concept_layer_select(options, [40, 1]) with pytest.raises(ValueError, match="unknown load-path concept layer selection"): arms.concept_variant({"loadpath_concept_layer_select": "knee"}) @@ -275,9 +275,10 @@ def test_cv_auc_dry_run_recipe_selects_one_layer_with_real_extraction(manifest): assert all(len(scores) == 2 for scores in direction.cv_scores.values()) -def test_cli_locks_concept_layer_select_variant_and_rejects_changes(tmp_path, monkeypatch): +def test_cli_locks_concept_layer_select_variant_and_rejects_changes(tmp_path, monkeypatch, manifest): root = tmp_path / "run" - base = ["--root", str(root), "--stages", "preflight", "--loadpath-causal-control"] + base = ["--root", str(root), "--stages", "preflight", "--loadpath-causal-control", + "--pain-pin", str(tmp_path / "pin")] argv = [*base, "--loadpath-concept-layer-select", "cv_auc"] def preflight(_root, _name, _command, output, _inputs, **_kwargs): @@ -313,3 +314,46 @@ def test_default_layer_select_adds_no_manifest_option(tmp_path, monkeypatch): "--loadpath-concept-layer-select", "all"])) options = campaign.read_json(root / "run-manifest.json")["locked_inputs"]["options"] assert "loadpath_concept_layer_select" not in options + + +def _never_launch(*_args, **_kwargs): + raise AssertionError("a stage worker launched before cv_auc inputs were validated") + + +@pytest.mark.parametrize("dry_run", [False, True]) +def test_cv_auc_rejects_too_small_explicit_cap_before_any_stage(tmp_path, monkeypatch, dry_run): + root = tmp_path / "run" + monkeypatch.setattr(campaign, "run_subprocess", _never_launch) + argv = ["--root", str(root), "--loadpath-concept-layer-select", "cv_auc", "--max-prompts", "1", + *(["--dry-run"] if dry_run else [])] + with pytest.raises(SystemExit): + campaign.parse_args(argv) + assert campaign.parse_args(["--root", str(root), "--max-prompts", "1"]).max_prompts == 1 + assert not root.exists() + + +def test_cv_auc_rejects_small_pinned_sets_before_any_stage_including_resume(tmp_path, monkeypatch, manifest): + pin = tmp_path / "pin" + rows = [row for row in campaign.read_json(pin / "datasets/3.1_pain_and_control_datasets.json") + ["datasets"]["S2_1P"]["sentences"] if row["category"] != "B" or row["prompt"].endswith(" 0")] + probes._write(pin / "datasets/3.1_pain_and_control_datasets.json", {"datasets": {"S2_1P": {"sentences": rows}}}) + monkeypatch.setattr(campaign, "run_subprocess", _never_launch) + root = tmp_path / "run" + argv = ["--root", str(root), "--loadpath-concept-layer-select", "cv_auc", "--pain-pin", str(pin)] + with pytest.raises(campaign.CampaignError, match=f"at least {arms.CV_AUC_MIN_PROMPTS} prompts in every set"): + campaign.campaign(campaign.parse_args(argv)) + assert not root.exists() + # A root locked before this check existed is refused on resume before preflight runs. + probes._write(root / "run-manifest.json", {"locked_inputs": {"options": {}}}) + locked = (root / "run-manifest.json").read_bytes() + with pytest.raises(campaign.CampaignError, match=f"at least {arms.CV_AUC_MIN_PROMPTS} prompts in every set"): + campaign.campaign(campaign.parse_args([*argv, "--resume"])) + assert (root / "run-manifest.json").read_bytes() == locked + assert sorted(path.name for path in root.iterdir()) == ["run-manifest.json"] + + +def test_loadpath_worker_rejects_impossible_cv_auc_before_gpu_steps(tmp_path, monkeypatch, manifest): + manifest["locked_inputs"]["options"].update(max_prompts=1, loadpath_concept_layer_select="cv_auc") + monkeypatch.setattr(probes, "_run_step", _never_launch) + with pytest.raises(ValueError, match=f"at least {arms.CV_AUC_MIN_PROMPTS} prompts in every set"): + probes.loadpath(manifest, tmp_path)