From c10fcff7e442c57ea7df03afa89efa4bf700ea6f Mon Sep 17 00:00:00 2001 From: Joseph Magly <1159087+jmagly@users.noreply.github.com> Date: Mon, 19 Oct 2026 14:08:01 -0400 Subject: [PATCH] fix(gpu): address silent-result review findings Co-Authored-By: Claude Opus 5.5 --- scripts/pain_axis_appendix_d.py | 1 + scripts/pain_axis_replication.py | 10 ++++ tests/test_pain_axis_appendix_d.py | 61 ++++++++++++++++++++++ tests/test_pain_axis_replication.py | 79 ++++++++++++++++++++++++++++- 4 files changed, 150 insertions(+), 1 deletion(-) diff --git a/scripts/pain_axis_appendix_d.py b/scripts/pain_axis_appendix_d.py index 819539ed..9c1b8724 100644 --- a/scripts/pain_axis_appendix_d.py +++ b/scripts/pain_axis_appendix_d.py @@ -140,6 +140,7 @@ def generate(model, tok, scenarios, fmt, batch_size, max_new_tokens): with torch.no_grad(): output = model.generate(**enc, max_new_tokens=max_new_tokens, do_sample=False, pad_token_id=tok.pad_token_id) + output = replication.first_sequences(model, output, enc["input_ids"].shape[0]) generations.extend(tok.batch_decode(output[:, enc["input_ids"].shape[1]:], skip_special_tokens=True)) return [{"id": row["id"], "category": row["category"], "generation": text} diff --git a/scripts/pain_axis_replication.py b/scripts/pain_axis_replication.py index f858c4fc..daaabb1b 100644 --- a/scripts/pain_axis_replication.py +++ b/scripts/pain_axis_replication.py @@ -206,6 +206,15 @@ def render(text, tok, fmt): return tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False) +def first_sequences(model, output, batch_size): + """Select the first returned candidate for each prompt without changing decoding.""" + output = getattr(output, "sequences", output) + count = getattr(getattr(model, "generation_config", None), "num_return_sequences", None) or 1 + if output.ndim != 2 or output.shape[0] != batch_size * count: + raise ValueError("Pain Axis generation returned an unexpected number of sequences") + return output[::count] + + def direction(vec, layer, name, model_id): return ConceptDirection(directions={layer: vec.float().cpu()}, extraction_layers=[layer], intervention_layers=[layer], concept_id=name, model_id=model_id) @@ -295,6 +304,7 @@ def stage_ablate(args): rec.clear() with torch.no_grad(): o = model.generate(**enc, max_new_tokens=60, do_sample=False, pad_token_id=tok.pad_token_id) + o = first_sequences(model, o, enc["input_ids"].shape[0]) gens += tok.batch_decode(o[:, enc["input_ids"].shape[1]:], skip_special_tokens=True) proj.append(torch.stack([p for _, p in rec]).mean(0)) # per-scenario mean |proj| for h in handles: diff --git a/tests/test_pain_axis_appendix_d.py b/tests/test_pain_axis_appendix_d.py index eeecc577..bb916683 100644 --- a/tests/test_pain_axis_appendix_d.py +++ b/tests/test_pain_axis_appendix_d.py @@ -221,6 +221,67 @@ def test_generation_preserves_prompt_rows_and_reference_decoding(monkeypatch): assert all(kwargs["padding_side"] == "left" for _, kwargs in calls) +@pytest.mark.parametrize("structured", [False, True]) +@pytest.mark.parametrize("return_sequences", [1, 2]) +def test_baseline_scores_first_candidate_per_scenario(tmp_path, monkeypatch, structured, return_sequences): + from transformers import BatchEncoding + from transformers.generation.utils import GenerateBeamDecoderOnlyOutput + + scenarios = [{"id": str(i), "category": "gaslighting", "text": str(i)} for i in range(100)] + data = tmp_path / "datasets" + data.mkdir() + (data / "4.1_self_other_420_scenarios.json").write_text(json.dumps(scenarios)) + batches = [] + + class Tokenizer: + pad_token_id = 0 + + def __call__(self, texts, **kwargs): + assert kwargs == {"return_tensors": "pt", "padding": True, "padding_side": "left"} + batches.append(texts) + return BatchEncoding({"input_ids": torch.tensor([[0, int(text) + 1] for text in texts])}) + + def batch_decode(self, output, **kwargs): + assert output.shape[1] == 1 + assert kwargs == {"skip_special_tokens": True} + return [f"joke alternative {token - 1001}" if token > 1000 else + f"joke {token - 1}" if token <= 25 else f"answer {token - 1}" + for token in output[:, 0].tolist()] + + class Generator: + device = "cpu" + model = SimpleNamespace(layers=[None] * 5) + generation_config = SimpleNamespace(num_beams=2, num_return_sequences=return_sequences, + return_dict_in_generate=structured) + + def generate(self, input_ids, **kwargs): + assert kwargs == {"max_new_tokens": 60, "do_sample": False, "pad_token_id": 0} + candidates = (input_ids[:, -1:] + 1000 * torch.arange(return_sequences)).reshape(-1, 1) + output = torch.cat([input_ids.repeat_interleave(return_sequences, dim=0), candidates], dim=1) + return GenerateBeamDecoderOnlyOutput(sequences=output) if structured else output + + model = Generator() + config = vars(model.generation_config).copy() + monkeypatch.setattr(appendix.ConceptDirection, "load", lambda path: direction()) + monkeypatch.setattr(appendix.replication, "MODELS", {"fixture": ("raw", 2, 2)}) + monkeypatch.setattr(appendix.replication, "load", lambda _: (Tokenizer(), model)) + monkeypatch.setattr(appendix.torch.cuda, "empty_cache", lambda: None) + values = args(model="fixture", direction="direction.safetensors", extraction_layer=2, + ranks="1", arms="baseline", pin=str(tmp_path), out=str(tmp_path / "out"), + name="fixture", batch_size=8, max_new_tokens=60) + appendix.run(values) + + rows = json.loads((tmp_path / "out/baseline.json").read_text()) + assert rows == [{"id": row["id"], "category": row["category"], + "generation": f"joke {i}" if i < 25 else f"answer {i}"} + for i, row in enumerate(scenarios)] + record = json.loads((tmp_path / "out/summary.json").read_text())["arms"]["baseline"] + assert record["status"] == "complete" and record["n"] == 100 + assert record["humor_proxy"] == 25 + assert [len(batch) for batch in batches] == [8] * 12 + [4] + assert vars(model.generation_config) == config + + def test_successful_sweep_runs_baseline_once_and_reloads_each_arm(tmp_path, monkeypatch): data = tmp_path / "datasets" data.mkdir() diff --git a/tests/test_pain_axis_replication.py b/tests/test_pain_axis_replication.py index 867cd09e..cec6a364 100644 --- a/tests/test_pain_axis_replication.py +++ b/tests/test_pain_axis_replication.py @@ -1,5 +1,6 @@ -"""Offline steering-stage regression against the phase-1 additive formula.""" +"""Offline generation alignment and steering-stage regressions.""" +import csv import json from types import SimpleNamespace @@ -44,6 +45,82 @@ class Decoder(nn.Module): return torch.cat([input_ids, torch.tensor([[7]])], dim=1) +@pytest.mark.parametrize("structured", [False, True]) +@pytest.mark.parametrize("return_sequences", [1, 2]) +def test_ablate_matches_official_first_candidate_per_scenario( + tmp_path, monkeypatch, structured, return_sequences, +): + from transformers.generation.utils import GenerateBeamDecoderOnlyOutput + + scenarios = [{"id": str(i), "category": "gaslighting", "text": str(i)} for i in range(100)] + data = tmp_path / "datasets" + data.mkdir() + (data / "4.1_self_other_420_scenarios.json").write_text(json.dumps(scenarios)) + results = tmp_path / "results/appC_ablation" + results.mkdir(parents=True) + with (results / "ablation_fixture.csv").open("w", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=["id", "condition", "generation"]) + writer.writeheader() + writer.writerows({"id": row["id"], "condition": "baseline", + "generation": f"answer {i}" if i >= 25 else "different"} + for i, row in enumerate(scenarios)) + batches, rec = [], [] + + class BatchTokenizer: + pad_token_id = 0 + + def __call__(self, texts, **kwargs): + assert kwargs == {"return_tensors": "pt", "padding": True, "padding_side": "left"} + batches.append(texts) + return BatchEncoding({"input_ids": torch.tensor([[0, int(text) + 1] for text in texts])}) + + def batch_decode(self, output, **kwargs): + assert output.shape[1] == 1 + assert kwargs == {"skip_special_tokens": True} + return [f"answer {token - 1}" for token in output[:, 0].tolist()] + + class Generator: + device = "cpu" + generation_config = SimpleNamespace(num_beams=2, num_return_sequences=return_sequences, + return_dict_in_generate=structured) + + def generate(self, input_ids, **kwargs): + assert kwargs == {"max_new_tokens": 60, "do_sample": False, "pad_token_id": 0} + candidates = (input_ids[:, -1:] + 1000 * torch.arange(return_sequences)).reshape(-1, 1) + output = torch.cat([input_ids.repeat_interleave(return_sequences, dim=0), candidates], dim=1) + rec.append((0, torch.ones(input_ids.shape[0] * 2, 4))) + return GenerateBeamDecoderOnlyOutput(sequences=output) if structured else output + + model = Generator() + config = vars(model.generation_config).copy() + monkeypatch.setattr(replication, "MODELS", {"fixture": ("raw", 0, 0)}) + monkeypatch.setattr(replication, "load", lambda _: (BatchTokenizer(), model)) + monkeypatch.setattr(replication.torch, "load", lambda *a, **kw: { + key: torch.ones(1, 3) for key in ("s1", "s2", "negemotion", "fear") + }) + monkeypatch.setattr(replication, "strict_monitor", lambda *a: (rec, [])) + monkeypatch.setattr(replication.torch.cuda, "empty_cache", lambda: None) + args = SimpleNamespace(pin=str(tmp_path), out=str(tmp_path), name="fixture", + model="offline/fixture", conditions="baseline", tag="") + replication.stage_ablate(args) + + rows = json.loads((tmp_path / "ablate/baseline.json").read_text()) + assert rows == [{"id": row["id"], "category": row["category"], "generation": f"answer {i}"} + for i, row in enumerate(scenarios)] + summary = json.loads((tmp_path / "ablate/summary.json").read_text())["baseline"] + assert summary["exact_match_official"] == 0.75 + assert summary["changed_vs_baseline_ours"] == 0 + assert [len(batch) for batch in batches] == [8] * 12 + [4] + assert vars(model.generation_config) == config + + +@pytest.mark.parametrize("shape", [(2, 3), (3, 3), (5, 3), (2, 2, 3)]) +def test_first_sequences_rejects_unexpected_candidate_count(shape): + model = SimpleNamespace(generation_config=SimpleNamespace(num_return_sequences=2)) + with pytest.raises(ValueError, match="Pain Axis generation returned an unexpected number of sequences"): + replication.first_sequences(model, torch.ones(shape), 2) + + @pytest.fixture def harness(tmp_path, monkeypatch): args = SimpleNamespace(pin=str(tmp_path / "pin"), out=str(tmp_path), name="fixture",