mirror of
https://github.com/elder-plinius/OBLITERATUS.git
synced 2026-12-05 02:24:12 +01:00
Merge pull request #692 from elder-plinius/fix/383-qwen38-concept-arm-variant
feat(qwen38): add a cv_auc concept-arm variant and record the loadpath-333 concept variant
This commit is contained in:
6 files changed
+361
-13
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
@@ -1472,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:
|
||||
@@ -1533,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()):
|
||||
@@ -1560,6 +1579,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()
|
||||
|
||||
@@ -4,6 +4,11 @@ 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
|
||||
# Every fold split needs a held-out prompt and a training prompt in each set.
|
||||
CV_AUC_MIN_PROMPTS = 2
|
||||
|
||||
|
||||
def selected_arms(options):
|
||||
@@ -22,6 +27,44 @@ 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 < 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}
|
||||
|
||||
|
||||
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,
|
||||
|
||||
@@ -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
|
||||
@@ -258,10 +261,12 @@ 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)
|
||||
# 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")
|
||||
@@ -277,6 +282,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(
|
||||
@@ -501,29 +507,47 @@ def _pipeline(model, tokenizer, manifest, root, *, concept=None):
|
||||
return pipeline
|
||||
|
||||
|
||||
def _concept_target(manifest):
|
||||
from obliteratus.concepts.target import ConceptTarget, ExtractionRecipe
|
||||
|
||||
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()}
|
||||
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[:_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 +597,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)
|
||||
|
||||
@@ -184,3 +184,176 @@ 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=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"})
|
||||
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, manifest):
|
||||
root = tmp_path / "run"
|
||||
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):
|
||||
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
|
||||
|
||||
|
||||
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)
|
||||
Reference in new issue
Block a user