-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_residual_patching_batch.py
More file actions
8373 lines (7730 loc) · 344 KB
/
Copy pathrun_residual_patching_batch.py
File metadata and controls
8373 lines (7730 loc) · 344 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Run residual-stream patching for one or more snippet pairs and save plots.
The sweep starts at the first prompt-token mismatch. For a causal decoder,
positions before that mismatch have identical prefixes, so patching them is
normally wasted work.
"""
from __future__ import annotations
import argparse
import ast
import csv
import difflib
import gc
import json
import math
import re
import shutil
import subprocess
import sys
import tempfile
import textwrap
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Tuple
if __package__ in (None, ""):
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from scripts.methodology_core import (
PAIR_FAMILIES,
PROMPT_ROLES,
StimulusPair,
classify_behavior,
clean_final_output_text,
iter_pair_dirs,
load_pair_dirs_from_args,
load_stimulus_pair,
)
pd = None
plt = None
torch = None
tqdm = None
SOURCE_RECOVERY_CMAP = "source_recovery"
DESTINATION_RECOVERY_CMAP = "destination_recovery"
SOURCE_LOGIT_MARGIN_CMAP = "source_logit_margin"
DESTINATION_LOGIT_MARGIN_CMAP = "destination_logit_margin"
SIGNED_SOURCE_POSITIVE_CMAP = "signed_source_positive"
SIGNED_DESTINATION_POSITIVE_CMAP = "signed_destination_positive"
CLEAN_RECOVERY_CMAP = SOURCE_RECOVERY_CMAP
CORRUPTED_RECOVERY_CMAP = DESTINATION_RECOVERY_CMAP
SEMANTIC_ROLE_CHOICES = (
"comment",
"docstring",
"function_name",
"variable_name",
"changed_cue_region",
"changed_implementation_region",
"input_example_object",
"output_readout",
"code_body",
"unknown",
)
DEFAULT_UNIT_TEST_PROMPT_TEMPLATE = (
"You are given a Python snippet. Generate one concise unit test (pytest style) with exactly "
"3 test cases for the main function defined in it. Each test case must be a single assertion "
"of the form `assert <expression> == <literal expected value>`. Do not use bare boolean "
"assertions such as `assert f(x)` or `assert not f(x)`; write `assert f(x) == True` or "
"`assert f(x) == False` instead. Return exactly one fenced Python code block. End the code "
"block with closing triple backticks.\n\n"
"```python\n{code}\n```\n\n"
"Unit test:\n"
)
UNIT_TEST_ASSERT_LIMIT = 3
MODEL_NAME_BY_SLUG = {
"codellama_7b_python_hf": "codellama/CodeLlama-7b-Python-hf",
"qwen2_5_7b_instruct": "Qwen/Qwen2.5-7B-Instruct",
"llama_3_1_8b_instruct": "meta-llama/Llama-3.1-8B-Instruct",
"mistral_7b_instruct_v0_1": "mistralai/Mistral-7B-Instruct-v0.1",
}
MODEL_SLUG_BY_NAME = {name: slug for slug, name in MODEL_NAME_BY_SLUG.items()}
RQ_STAGES = ("rq1_1", "rq1_2", "rq2_1", "rq2_2")
RQ_STAGE_DIRS = {
"rq1_1": "rq1_1_final_output_generation",
"rq1_2": "rq1_2_final_output_residual_patching",
"rq2_1": "rq2_1_unit_test_generation",
"rq2_2": "rq2_2_unit_test_residual_patching",
}
def repo_root() -> Path:
return Path(__file__).resolve().parents[1]
def load_runtime_dependencies() -> None:
global pd, plt, torch, tqdm
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as _plt
import pandas as _pd
import torch as _torch
from tqdm.auto import tqdm as _tqdm
_plt.rcParams.update({"pdf.fonttype": 42, "ps.fonttype": 42})
pd = _pd
plt = _plt
torch = _torch
tqdm = _tqdm
def load_hooked_transformer_class():
try:
from transformer_lens import HookedTransformer
except Exception as e: # pragma: no cover - import guard for user environment
raise ImportError(
"transformer_lens is required. Install it with: pip install transformer_lens"
) from e
return HookedTransformer
def cleanup_runtime_memory() -> None:
gc.collect()
if torch is None:
return
if hasattr(torch, "cuda") and torch.cuda.is_available():
torch.cuda.empty_cache()
if hasattr(torch.cuda, "ipc_collect"):
torch.cuda.ipc_collect()
if hasattr(torch, "mps") and hasattr(torch.mps, "empty_cache"):
try:
torch.mps.empty_cache()
except RuntimeError:
pass
def pair_dir_display_name(pair_dir: Path, stimulus_root: Path) -> str:
try:
return pair_dir.relative_to(stimulus_root).as_posix()
except ValueError:
return pair_dir.name
def stimulus_pair_to_runner_pair(pair: StimulusPair, pair_dir: Path) -> Dict[str, Any]:
return {
"pair_dir": pair_dir,
"pair_id": pair.pair_id,
"pair_family": pair.pair_family,
"prompts": pair.prompts,
"patch_directions": pair.patch_directions,
"meta": {
"pair_id": pair.pair_id,
"pair_family": pair.pair_family,
"prompts": {
role: {
"file": prompt.file,
"prompt_role": prompt.role,
"execution_output": prompt.execution_output,
"cue_output": prompt.cue_output,
}
for role, prompt in pair.prompts.items()
},
},
"prompt_codes": {role: prompt.code for role, prompt in pair.prompts.items()},
}
def resolve_pair_dir(stimulus_root: Path, pair_name: str) -> Path:
matches = load_pair_dirs_from_args(
stimulus_root=stimulus_root,
names=[pair_name],
use_all=False,
)
if not matches:
raise FileNotFoundError(f"Stimulus pair folder not found: {pair_name}")
return matches[0]
def load_pair(snippet_dir: Path, pair_name: str) -> Dict:
pair_dir = resolve_pair_dir(snippet_dir, pair_name)
return stimulus_pair_to_runner_pair(load_stimulus_pair(pair_dir), pair_dir)
def list_pairs(snippet_dir: Path, pair_family: Optional[str] = None) -> List[str]:
names = []
for pair_dir in iter_pair_dirs(snippet_dir):
pair = load_stimulus_pair(pair_dir)
if pair_family and pair.pair_family != pair_family:
continue
names.append(pair_dir_display_name(pair_dir, snippet_dir))
return sorted(names)
def build_prompt(code: str, template: str) -> str:
return template.format(code=code.rstrip())
def fenced_code_match(text: str) -> Optional[re.Match[str]]:
match = re.search(r"```[^\n`]*\n(.*?)\n```", text, flags=re.DOTALL)
if match:
return match
return re.search(r"```(.*?)```", text, flags=re.DOTALL)
def split_fenced_prompt(prompt: str) -> Dict[str, str]:
match = fenced_code_match(prompt)
if not match:
return {
"prompt_text": prompt.strip(),
"snippet_text": "",
"prefix_text": prompt,
"suffix_text": "",
}
prefix = prompt[: match.start()]
snippet = match.group(1).strip("\n")
suffix = prompt[match.end() :]
return {
"prompt_text": prefix.strip(),
"snippet_text": snippet,
"prefix_text": prefix,
"suffix_text": suffix,
}
def prompt_output_label(prompt_parts: Dict[str, str], fallback: str = "Generated Answer") -> str:
label = str(prompt_parts.get("suffix_text") or "").strip()
return label or fallback
def fenced_code_body_span(prompt: str) -> Optional[Tuple[int, int]]:
match = fenced_code_match(prompt)
if not match:
return None
return int(match.start(1)), int(match.end(1))
def fenced_code_and_output_cue_span(prompt: str) -> Optional[Tuple[int, int]]:
match = fenced_code_match(prompt)
if not match:
return None
return int(match.start(1)), len(prompt)
def display_model_token(token: str) -> str:
return str(token).replace("\u0120", " ").replace("\u2581", " ").replace("Ċ", "\n")
def normalize_token_match_text(text: str) -> str:
return display_model_token(text).replace("\r\n", "\n").replace("\r", "\n").strip()
def token_span_in_text(source: str, start_index: int, raw_token: str) -> Tuple[int, int]:
token = display_model_token(raw_token)
if not token:
return start_index, start_index
if source.startswith(token, start_index):
return start_index, start_index + len(token)
if token.startswith(" ") and source.startswith(token[1:], start_index):
return start_index, start_index + len(token[1:])
if token and all(ch.isspace() for ch in token):
end = start_index
limit = min(len(source), start_index + max(1, len(token)))
while end < limit and source[end].isspace():
end += 1
return start_index, end
normalized_token = normalize_token_match_text(token)
if not normalized_token:
return start_index, start_index
search_limit = min(len(source), start_index + 96)
best_start = source.find(token, start_index, search_limit)
if best_start >= 0:
return best_start, best_start + len(token)
stripped = token.strip()
if stripped:
best_start = source.find(stripped, start_index, search_limit)
if best_start >= 0:
return best_start, best_start + len(stripped)
return start_index, start_index
def token_positions_overlapping_span(
source: str,
token_strs: Sequence[str],
char_span: Optional[Tuple[int, int]],
) -> List[int]:
if char_span is None:
return []
span_start, span_end = int(char_span[0]), int(char_span[1])
positions: List[int] = []
cursor = 0
for pos, raw_token in enumerate(token_strs):
token_start, token_end = token_span_in_text(source, cursor, raw_token)
if token_end > span_start and token_start < span_end:
positions.append(int(pos))
cursor = max(cursor, token_end)
return positions
def filter_patch_units_to_position_sets(
patch_units: Sequence["PatchUnit"],
clean_positions: Sequence[int],
corrupted_positions: Sequence[int],
) -> List["PatchUnit"]:
clean_set = {int(pos) for pos in clean_positions}
corrupted_set = {int(pos) for pos in corrupted_positions}
filtered: List[PatchUnit] = []
for unit in patch_units:
if not unit.clean_positions or not unit.corrupted_positions:
continue
if all(int(pos) in clean_set for pos in unit.clean_positions) and all(
int(pos) in corrupted_set for pos in unit.corrupted_positions
):
filtered.append(unit)
return filtered
def extract_completion(full_text: str, prompt: str) -> str:
if full_text.startswith(prompt):
return full_text[len(prompt) :].strip()
return full_text.strip()
def truncate_after_first_fenced_block(text: str) -> str:
opener = text.find("```")
if opener < 0:
return text
closer = text.find("```", opener + 3)
if closer < 0:
return text
return text[: closer + 3]
def contains_complete_fenced_block(text: str) -> bool:
opener = text.find("```")
return opener >= 0 and text.find("```", opener + 3) >= 0
def extract_first_fenced_block(text: str) -> str:
match = re.search(r"```[^\n`]*\n(.*?)```", text, flags=re.DOTALL)
if not match:
match = re.search(r"```(.*?)```", text, flags=re.DOTALL)
if not match:
return text.strip()
return match.group(1).strip()
def extract_first_fenced_block_or_empty(text: str) -> str:
match = re.search(r"```[^\n`]*\n(.*?)```", text, flags=re.DOTALL)
if not match:
match = re.search(r"```(.*?)```", text, flags=re.DOTALL)
if not match:
return ""
return match.group(1).strip()
def extract_first_fenced_block_or_text(text: str) -> str:
extracted = extract_first_fenced_block_or_empty(text)
return extracted if extracted else text.strip()
def split_first_fenced_block_prefix_body(text: str) -> Optional[Tuple[str, str, bool]]:
opener = text.find("```")
if opener < 0:
return None
header_end = text.find("\n", opener + 3)
if header_end < 0:
return None
body_start = header_end + 1
closer = text.find("```", body_start)
if closer < 0:
return text[:body_start], text[body_start:], False
return text[:body_start], text[body_start:closer], True
def parsed_assertion_spans(source: str) -> Optional[List[Tuple[int, int]]]:
try:
tree = ast.parse(source)
except SyntaxError:
return None
spans: List[Tuple[int, int]] = []
for node in ast.walk(tree):
if not isinstance(node, ast.Assert):
continue
span = node_char_span(source, node)
if span is not None:
spans.append((int(span[0]), int(span[1])))
return sorted(spans)
def parsed_supported_equality_assertion_spans(source: str) -> Optional[List[Tuple[int, int]]]:
try:
tree = ast.parse(source)
except SyntaxError:
return None
spans: List[Tuple[int, int]] = []
for node in ast.walk(tree):
if not isinstance(node, ast.Assert):
continue
test = node.test
if not isinstance(test, ast.Compare):
continue
if len(test.ops) != 1 or not isinstance(test.ops[0], ast.Eq):
continue
if len(test.comparators) != 1:
continue
span = node_char_span(source, node)
if span is not None:
spans.append((int(span[0]), int(span[1])))
return sorted(spans)
def cap_unit_test_source_to_assert_limit(
test_source: str,
max_asserts: int = UNIT_TEST_ASSERT_LIMIT,
) -> str:
source = str(test_source or "").strip()
if max_asserts <= 0:
return ""
supported_spans = parsed_supported_equality_assertion_spans(source)
if supported_spans is not None and len(supported_spans) >= max_asserts:
return source[: supported_spans[max_asserts - 1][1]].rstrip()
spans = parsed_assertion_spans(source)
if spans is None or len(spans) <= max_asserts:
return source
if supported_spans:
return source
return source[: spans[max_asserts - 1][1]].rstrip()
def unit_test_assert_limit_reached(
completion: str,
max_asserts: int = UNIT_TEST_ASSERT_LIMIT,
) -> bool:
parts = split_first_fenced_block_prefix_body(completion)
candidate = parts[1] if parts is not None else completion
spans = parsed_supported_equality_assertion_spans(str(candidate or "").strip())
return spans is not None and len(spans) >= max_asserts
def cap_unit_test_completion_to_assert_limit(
completion: str,
max_asserts: int = UNIT_TEST_ASSERT_LIMIT,
) -> str:
completion = str(completion or "")
parts = split_first_fenced_block_prefix_body(completion)
if parts is None:
return cap_unit_test_source_to_assert_limit(completion, max_asserts=max_asserts).strip()
prefix, body, has_closer = parts
capped_body = cap_unit_test_source_to_assert_limit(body, max_asserts=max_asserts)
capped_spans = parsed_supported_equality_assertion_spans(capped_body)
reached_limit = capped_spans is not None and len(capped_spans) >= max_asserts
if reached_limit:
return f"{prefix}{capped_body}\n```".strip()
if has_closer:
return truncate_after_first_fenced_block(completion).strip()
return completion.strip()
def extract_first_json_object(text: str) -> str:
stripped = extract_first_fenced_block_or_text(text).strip()
if stripped.startswith("{") and stripped.endswith("}"):
return stripped
start = stripped.find("{")
if start < 0:
return stripped
depth = 0
in_string = False
escape = False
for index, ch in enumerate(stripped[start:], start=start):
if in_string:
if escape:
escape = False
elif ch == "\\":
escape = True
elif ch == '"':
in_string = False
continue
if ch == '"':
in_string = True
elif ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return stripped[start : index + 1]
return stripped[start:]
def compact_token_id_label(token_ids: Optional[Sequence[int]]) -> str:
ids = [int(token_id) for token_id in (token_ids or [])]
if not ids:
return ""
if len(ids) == 1:
return str(ids[0])
shown = ",".join(str(token_id) for token_id in ids[:3])
return shown if len(ids) <= 3 else shown + ",..."
def format_whitespace_for_axis(text: str) -> str:
if text == " ":
return "<space>"
if text and set(text) == {" "}:
return f"<{len(text)} spaces>"
if text == "\n":
return "<newline>"
if text and set(text) == {"\n"}:
return f"<{len(text)} newlines>"
if text == "\t":
return "<tab>"
if text and set(text) == {"\t"}:
return f"<{len(text)} tabs>"
escaped = (
text.replace(" ", "·")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t")
)
return f"<ws:{escaped}>"
def format_text_for_axis(
text: str,
max_chars: int = 18,
token_ids: Optional[Sequence[int]] = None,
) -> str:
raw_text = str(text).replace("\u0120", " ").replace("\u2581", " ")
if raw_text == "":
label = "<empty>"
elif raw_text.isspace():
label = format_whitespace_for_axis(raw_text)
else:
label = raw_text.replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t")
if raw_text.strip() != raw_text:
label = repr(label)
if len(label) > max_chars:
label = label[: max_chars - 3] + "..."
return label
def format_token_for_axis(
token: str,
max_chars: int = 18,
token_ids: Optional[Sequence[int]] = None,
) -> str:
return format_text_for_axis(token, max_chars=max_chars, token_ids=token_ids)
def format_span_for_axis(
text: str,
max_chars: int = 18,
token_ids: Optional[Sequence[int]] = None,
) -> str:
return format_text_for_axis(text, max_chars=max_chars, token_ids=token_ids)
def recovery_cmap_for_flow_direction(flow_direction: str) -> str:
if str(flow_direction).startswith(("aligned_cue_to", "aligned_implementation_to")):
return SOURCE_RECOVERY_CMAP
return DESTINATION_RECOVERY_CMAP
def get_variant_code(pair: Dict, variant: str) -> str:
prompt_codes = pair.get("prompt_codes")
if isinstance(prompt_codes, dict) and variant in prompt_codes:
return str(prompt_codes[variant])
raise ValueError(f"Unknown prompt_role: {variant!r}.")
def execute_snippet_and_get_final_printed_output(code: str) -> Optional[str]:
import io
from contextlib import redirect_stdout
stdout_buffer = io.StringIO()
exec_scope = {"__builtins__": __builtins__}
try:
with redirect_stdout(stdout_buffer):
exec(code, exec_scope, exec_scope)
except Exception:
return None
lines = stdout_buffer.getvalue().splitlines()
return lines[-1] if lines else None
@dataclass
class AnswerDecisionSpec:
answer_resolution_schema: str
clean_positive_answer: str
clean_negative_answer: Optional[str]
corrupted_positive_answer: Optional[str]
corrupted_negative_answer: Optional[str]
forward_positive_answer: str
forward_negative_answer: Optional[str]
reverse_positive_answer: Optional[str]
reverse_negative_answer: Optional[str]
clean_expected_output: Optional[str]
corrupted_expected_output: Optional[str]
def optional_str(value: Any) -> Optional[str]:
return None if value is None else str(value)
def variant_metadata_value(meta: Dict[str, Any], mapping_key: str, variant: str) -> Optional[str]:
mapping = meta.get(mapping_key)
if isinstance(mapping, dict) and variant in mapping:
return optional_str(mapping[variant])
return None
def flat_variant_metadata_value(meta: Dict[str, Any], variant: str, suffix: str) -> Optional[str]:
return optional_str(meta.get(f"{variant}_{suffix}"))
def resolve_variant_answer(meta: Dict[str, Any], variant: str) -> Optional[str]:
return (
variant_metadata_value(meta, "answers", variant)
or variant_metadata_value(meta, "variant_answers", variant)
or flat_variant_metadata_value(meta, variant, "answer")
)
def resolve_variant_wrong_answer(meta: Dict[str, Any], variant: str) -> Optional[str]:
return (
variant_metadata_value(meta, "wrong_answers", variant)
or variant_metadata_value(meta, "variant_wrong_answers", variant)
or flat_variant_metadata_value(meta, variant, "wrong_answer")
)
def has_variant_answer_metadata(meta: Dict[str, Any]) -> bool:
return any(
key in meta
for key in (
"answers",
"variant_answers",
"wrong_answers",
"variant_wrong_answers",
"control_answer",
"control_wrong_answer",
"treatment_answer",
"treatment_wrong_answer",
)
)
def explicit_direction_decision(
meta: Dict[str, Any],
source_variant: str,
destination_variant: str,
role_key: str,
) -> Tuple[Optional[str], Optional[str]]:
decisions = meta.get("answer_decisions")
if not isinstance(decisions, dict):
return None, None
for key in (
f"{source_variant}_into_{destination_variant}",
role_key,
):
decision = decisions.get(key)
if not isinstance(decision, dict):
continue
positive = optional_str(
decision.get("positive_answer", decision.get("positive", decision.get("answer")))
)
negative = optional_str(
decision.get(
"negative_answer",
decision.get("negative", decision.get("wrong_answer")),
)
)
return positive, negative
return None, None
def legacy_answer_decision_spec(
*,
target: str,
wrong: Optional[str],
clean_expected_output: Optional[str],
corrupted_expected_output: Optional[str],
answer_resolution_schema: str,
) -> AnswerDecisionSpec:
return AnswerDecisionSpec(
answer_resolution_schema=answer_resolution_schema,
clean_positive_answer=target,
clean_negative_answer=wrong,
corrupted_positive_answer=wrong,
corrupted_negative_answer=target if wrong is not None else None,
forward_positive_answer=target,
forward_negative_answer=wrong,
reverse_positive_answer=wrong,
reverse_negative_answer=target if wrong is not None else None,
clean_expected_output=clean_expected_output,
corrupted_expected_output=corrupted_expected_output,
)
def resolve_answer_decision_spec(
pair: Dict,
clean_variant: str,
corrupted_variant: str,
clean_code: str,
corrupted_code: str,
use_gold_answer: bool = True,
manual_target_answer: Optional[str] = None,
manual_wrong_answer: Optional[str] = None,
force_target_to_clean_output: bool = True,
auto_wrong_from_corrupted_output: bool = True,
) -> AnswerDecisionSpec:
meta = pair["meta"]
clean_output = execute_snippet_and_get_final_printed_output(clean_code)
corrupted_output = execute_snippet_and_get_final_printed_output(corrupted_code)
prompts = pair.get("prompts")
if isinstance(prompts, dict) and clean_variant in prompts and corrupted_variant in prompts:
source_prompt = prompts[clean_variant]
destination_prompt = prompts[corrupted_variant]
pair_family = str(pair.get("pair_family") or meta.get("pair_family") or "")
if pair_family == "cue_varied":
source_value = str(source_prompt.cue_output)
destination_value = str(destination_prompt.cue_output)
elif pair_family == "implementation_varied":
source_value = str(source_prompt.execution_output)
destination_value = str(destination_prompt.execution_output)
else:
raise ValueError(f"Unsupported pair_family: {pair_family!r}")
if clean_output is not None and clean_output != source_prompt.execution_output:
raise ValueError("runtime_metadata_mismatch")
if corrupted_output is not None and corrupted_output != destination_prompt.execution_output:
raise ValueError("runtime_metadata_mismatch")
return AnswerDecisionSpec(
answer_resolution_schema="methodology_schema",
clean_positive_answer=source_value,
clean_negative_answer=destination_value,
corrupted_positive_answer=destination_value,
corrupted_negative_answer=source_value,
forward_positive_answer=source_value,
forward_negative_answer=destination_value,
reverse_positive_answer=destination_value,
reverse_negative_answer=source_value,
clean_expected_output=str(source_prompt.execution_output),
corrupted_expected_output=str(destination_prompt.execution_output),
)
if not use_gold_answer or manual_target_answer is not None or manual_wrong_answer is not None:
target = meta.get("answer") if use_gold_answer and manual_target_answer is None else manual_target_answer
if target is None:
raise ValueError("No target answer resolved. Set --manual-target-answer or use metadata.")
target = str(target)
wrong = meta.get("wrong_answer") if manual_wrong_answer is None else manual_wrong_answer
wrong = optional_str(wrong)
if (
force_target_to_clean_output
and use_gold_answer
and manual_target_answer is None
and clean_output is not None
and clean_output != target
):
target = clean_output
if (
auto_wrong_from_corrupted_output
and manual_wrong_answer is None
and corrupted_output is not None
and corrupted_output != target
):
wrong = corrupted_output
return legacy_answer_decision_spec(
target=target,
wrong=wrong,
clean_expected_output=clean_output,
corrupted_expected_output=corrupted_output,
answer_resolution_schema="manual_or_legacy",
)
forward_positive, forward_negative = explicit_direction_decision(
meta,
source_variant=clean_variant,
destination_variant=corrupted_variant,
role_key="clean_into_corrupted",
)
reverse_positive, reverse_negative = explicit_direction_decision(
meta,
source_variant=corrupted_variant,
destination_variant=clean_variant,
role_key="corrupted_into_clean",
)
if forward_positive is not None or reverse_positive is not None:
if forward_positive is None:
raise ValueError("answer_decisions is missing the forward positive answer.")
return AnswerDecisionSpec(
answer_resolution_schema="answer_decisions",
clean_positive_answer=forward_positive,
clean_negative_answer=forward_negative,
corrupted_positive_answer=reverse_positive,
corrupted_negative_answer=reverse_negative,
forward_positive_answer=forward_positive,
forward_negative_answer=forward_negative,
reverse_positive_answer=reverse_positive,
reverse_negative_answer=reverse_negative,
clean_expected_output=clean_output,
corrupted_expected_output=corrupted_output,
)
if has_variant_answer_metadata(meta):
clean_positive = resolve_variant_answer(meta, clean_variant)
corrupted_positive = resolve_variant_answer(meta, corrupted_variant)
if force_target_to_clean_output and clean_output is not None:
clean_positive = clean_output
if force_target_to_clean_output and corrupted_output is not None:
corrupted_positive = corrupted_output
if clean_positive is None:
clean_positive = optional_str(meta.get("answer"))
if corrupted_positive is None:
corrupted_positive = corrupted_output
if clean_positive is None:
raise ValueError(f"No positive answer resolved for {clean_variant!r}.")
if corrupted_positive is None:
raise ValueError(f"No positive answer resolved for {corrupted_variant!r}.")
clean_negative = resolve_variant_wrong_answer(meta, clean_variant)
corrupted_negative = resolve_variant_wrong_answer(meta, corrupted_variant)
if clean_negative is None and corrupted_positive != clean_positive:
clean_negative = corrupted_positive
if corrupted_negative is None and clean_positive != corrupted_positive:
corrupted_negative = clean_positive
return AnswerDecisionSpec(
answer_resolution_schema="variant_answers",
clean_positive_answer=str(clean_positive),
clean_negative_answer=clean_negative,
corrupted_positive_answer=str(corrupted_positive),
corrupted_negative_answer=corrupted_negative,
forward_positive_answer=str(clean_positive),
forward_negative_answer=clean_negative,
reverse_positive_answer=str(corrupted_positive),
reverse_negative_answer=corrupted_negative,
clean_expected_output=clean_output,
corrupted_expected_output=corrupted_output,
)
target = meta.get("answer")
if target is None:
raise ValueError("No target answer resolved. Set --manual-target-answer or use metadata.")
target = str(target)
wrong = optional_str(meta.get("wrong_answer"))
if (
force_target_to_clean_output
and clean_output is not None
and clean_output != target
):
target = clean_output
if (
auto_wrong_from_corrupted_output
and corrupted_output is not None
and corrupted_output != target
):
wrong = corrupted_output
return legacy_answer_decision_spec(
target=target,
wrong=wrong,
clean_expected_output=clean_output,
corrupted_expected_output=corrupted_output,
answer_resolution_schema="legacy_answer_wrong_answer",
)
def resolve_target_and_wrong_answers(
pair: Dict,
clean_code: str,
corrupted_code: str,
use_gold_answer: bool = True,
manual_target_answer: Optional[str] = None,
manual_wrong_answer: Optional[str] = None,
force_target_to_clean_output: bool = True,
auto_wrong_from_corrupted_output: bool = True,
) -> Tuple[str, Optional[str], Optional[str], Optional[str]]:
spec = resolve_answer_decision_spec(
pair=pair,
clean_variant="control",
corrupted_variant="treatment",
clean_code=clean_code,
corrupted_code=corrupted_code,
use_gold_answer=use_gold_answer,
manual_target_answer=manual_target_answer,
manual_wrong_answer=manual_wrong_answer,
force_target_to_clean_output=force_target_to_clean_output,
auto_wrong_from_corrupted_output=auto_wrong_from_corrupted_output,
)
return (
spec.forward_positive_answer,
spec.forward_negative_answer,
spec.clean_expected_output,
spec.corrupted_expected_output,
)
def slugify(value: str) -> str:
value = re.sub(r"[^A-Za-z0-9_.-]+", "_", value.strip())
return value.strip("._") or "pair"
def role_kind(role: Any) -> str:
text = str(role or "")
if text.startswith("aligned_"):
return "aligned"
if text.startswith("conflicting_"):
return "conflicting"
return "unknown"
def parse_stage_csv(value: Optional[str], *, default: Sequence[str] = ()) -> Set[str]:
if value is None or str(value).strip() == "":
return set(default)
stages = {
part.strip().lower().replace(".", "_")
for part in str(value).split(",")
if part.strip()
}
invalid = sorted(stages.difference(RQ_STAGES))
if invalid:
raise ValueError(
f"Invalid RQ stage(s): {', '.join(invalid)}. "
f"Expected comma-separated values from: {', '.join(RQ_STAGES)}"
)
return stages
def resolve_model_name_and_slug(
model_arg: Optional[str],
model_name: str,
model_slug: Optional[str],
) -> Tuple[str, str]:
selected = str(model_arg or model_name or "").strip()
if model_arg and selected in MODEL_NAME_BY_SLUG:
resolved_name = MODEL_NAME_BY_SLUG[selected]
resolved_slug = selected
else:
resolved_name = MODEL_NAME_BY_SLUG.get(selected, selected)
resolved_slug = model_slug or MODEL_SLUG_BY_NAME.get(resolved_name) or slugify(resolved_name).lower()
if model_slug:
resolved_slug = str(model_slug)
return resolved_name, resolved_slug
def rq_pair_output_dir(
output_root: Path,
model_slug: str,
pair_family: str,
pair_id: str,
) -> Path:
return output_root / str(model_slug) / str(pair_family) / str(pair_id)
def rq_stage_dir(pair_dir: Path, stage: str) -> Path:
return pair_dir / RQ_STAGE_DIRS[stage]
def load_json_dict(path: Path) -> Optional[Dict[str, Any]]:
if not path.exists():
return None
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return None
return payload if isinstance(payload, dict) else None
def write_json_dict(path: Path, payload: Dict[str, Any]) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2, default=str) + "\n", encoding="utf-8")