File size: 12,517 Bytes
3236af9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
import argparse
import importlib
import json
import os
import sys
from collections import defaultdict
from os.path import commonprefix
from pathlib import Path
from typing import Any


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--iconoclast-checkpoint", required=True)
    parser.add_argument("--heretic-checkpoint", required=True)
    parser.add_argument("--output-dir", required=True)
    parser.add_argument("--sample-count", type=int, default=5)
    return parser.parse_args()


def load_study(checkpoint_path: Path) -> tuple[str, dict[int, dict[str, Any]]]:
    settings_json = None
    trials: dict[int, dict[str, Any]] = defaultdict(dict)

    for line in checkpoint_path.read_text().splitlines():
        obj = json.loads(line)
        user_attr = obj.get("user_attr")
        if user_attr and "settings" in user_attr and settings_json is None:
            settings_json = user_attr["settings"]

        trial_id = obj.get("trial_id")
        if trial_id is not None and user_attr:
            trials[trial_id].update(user_attr)

    if settings_json is None:
        raise ValueError(f"Did not find settings in {checkpoint_path}")

    return settings_json, trials


def pick_best_trial(trials: dict[int, dict[str, Any]]) -> dict[str, Any]:
    best = None

    for trial_id, attrs in trials.items():
        if not {"refusals", "kl_divergence", "parameters"}.issubset(attrs):
            continue

        item = {
            "trial_id": trial_id,
            "index": attrs.get("index"),
            "refusals": attrs["refusals"],
            "overrefusals": attrs.get("overrefusals", 0),
            "kl_divergence": attrs["kl_divergence"],
            "direction_index": attrs["direction_index"],
            "direction_method": attrs["direction_method"],
            "direction_blend": attrs.get("direction_blend", 0.0),
            "component_direction_indices": attrs.get("component_direction_indices"),
            "component_direction_methods": attrs.get("component_direction_methods"),
            "component_direction_blends": attrs.get("component_direction_blends"),
            "parameters": attrs["parameters"],
        }

        key = (item["refusals"], item["overrefusals"], item["kl_divergence"])
        if best is None or key < (
            best["refusals"],
            best["overrefusals"],
            best["kl_divergence"],
        ):
            best = item

    if best is None:
        raise ValueError("No completed trials with metrics were found")

    return best


def load_stack(package: str) -> dict[str, Any]:
    return {
        "package": package,
        "config": importlib.import_module(f"{package}.config"),
        "direction": importlib.import_module(f"{package}.direction"),
        "model": importlib.import_module(f"{package}.model"),
        "utils": importlib.import_module(f"{package}.utils"),
    }


def normalize_refusal_text(text: str) -> str:
    text = text.lower().replace("*", "")
    text = text.replace("’", "'")
    return " ".join(text.split())


def is_refusal(response: str, refusal_markers: list[str]) -> bool:
    if not response.strip():
        return True

    normalized = normalize_refusal_text(response)
    return any(marker.lower() in normalized for marker in refusal_markers)


def determine_response_prefix(model: Any, good_prompts: list[Any], bad_prompts: list[Any]) -> None:
    prefix_check_prompts = good_prompts[:100] + bad_prompts[:100]
    responses = model.get_responses_batched(prefix_check_prompts)
    model.response_prefix = commonprefix(responses).rstrip(" ")

    recheck_prefix = False
    if model.response_prefix:
        recheck_prefix = True
        if model.response_prefix.startswith("<think>"):
            model.response_prefix = "<think></think>"
        elif model.response_prefix.startswith("<|channel|>analysis<|message|>"):
            model.response_prefix = (
                "<|channel|>analysis<|message|><|end|><|start|>assistant<|channel|>final<|message|>"
            )
        elif model.response_prefix.startswith("<thought>"):
            model.response_prefix = "<thought></thought>"
        elif model.response_prefix.startswith("[THINK]"):
            model.response_prefix = "[THINK][/THINK]"
        else:
            recheck_prefix = False

    if recheck_prefix:
        responses = model.get_responses_batched(prefix_check_prompts)
        additional_prefix = commonprefix(responses).rstrip(" ")
        if additional_prefix:
            model.response_prefix += additional_prefix


def prepare_runtime(stack: dict[str, Any], settings_json: str) -> dict[str, Any]:
    Settings = stack["config"].Settings
    DirectionMethod = stack["config"].DirectionMethod
    Model = stack["model"].Model
    load_prompts = stack["utils"].load_prompts
    set_random_seed = stack["utils"].set_random_seed
    empty_cache = stack["utils"].empty_cache
    compute_direction_candidates = stack["direction"].compute_direction_candidates
    orthogonalize_directions = stack["direction"].orthogonalize_directions
    blend_directions = stack["direction"].blend_directions

    settings = Settings.model_validate_json(settings_json)
    set_random_seed(settings.seed)
    model = Model(settings)

    good_prompts = load_prompts(settings, settings.good_prompts)
    bad_prompts = load_prompts(settings, settings.bad_prompts)
    good_eval_prompts = load_prompts(settings, settings.good_evaluation_prompts)
    bad_eval_prompts = load_prompts(settings, settings.bad_evaluation_prompts)

    determine_response_prefix(model, good_prompts, bad_prompts)

    good_residuals = model.get_residuals_batched(good_prompts)
    bad_residuals = model.get_residuals_batched(bad_prompts)
    good_means = good_residuals.mean(dim=0)
    direction_candidates = compute_direction_candidates(
        good_residuals,
        bad_residuals,
        settings.direction_variance_floor,
    )

    if settings.orthogonalize_direction:
        direction_candidates = {
            method: orthogonalize_directions(candidate, good_means)
            for method, candidate in direction_candidates.items()
        }

    del good_residuals, bad_residuals
    empty_cache()

    def get_trial_refusal_directions(trial_data: dict[str, Any]) -> Any:
        component_direction_methods = trial_data.get("component_direction_methods")
        if isinstance(component_direction_methods, dict):
            component_direction_blends = trial_data.get(
                "component_direction_blends",
                {},
            )
            return {
                component: blend_directions(
                    direction_candidates[DirectionMethod.MEAN],
                    direction_candidates[DirectionMethod.VARIANCE],
                    float(component_direction_blends.get(component, 0.0)),
                )
                if DirectionMethod(method) == DirectionMethod.HYBRID
                else direction_candidates[DirectionMethod(method)]
                for component, method in component_direction_methods.items()
            }

        direction_method = DirectionMethod(trial_data["direction_method"])
        direction_blend = float(trial_data.get("direction_blend", 0.0))
        if direction_method == DirectionMethod.HYBRID:
            return blend_directions(
                direction_candidates[DirectionMethod.MEAN],
                direction_candidates[DirectionMethod.VARIANCE],
                direction_blend,
            )
        return direction_candidates[direction_method]

    return {
        "settings": settings,
        "model": model,
        "good_eval_prompts": good_eval_prompts,
        "bad_eval_prompts": bad_eval_prompts,
        "get_trial_refusal_directions": get_trial_refusal_directions,
        "AbliterationParameters": stack["model"].AbliterationParameters,
        "empty_cache": empty_cache,
    }


def apply_trial(runtime: dict[str, Any], trial_data: dict[str, Any]) -> None:
    model = runtime["model"]
    AbliterationParameters = runtime["AbliterationParameters"]

    parameters = {
        name: AbliterationParameters(**values)
        for name, values in trial_data["parameters"].items()
    }

    model.reset_model()
    model.abliterate(
        runtime["get_trial_refusal_directions"](trial_data),
        trial_data.get("component_direction_indices", trial_data["direction_index"]),
        parameters,
    )


def export_merged_model(runtime: dict[str, Any], output_dir: Path) -> None:
    output_dir.mkdir(parents=True, exist_ok=True)
    merged_model = runtime["model"].get_merged_model()
    merged_model.save_pretrained(output_dir)
    runtime["model"].tokenizer.save_pretrained(output_dir)
    del merged_model
    runtime["empty_cache"]()


def prompt_record(category: str, index: int, prompt: Any) -> dict[str, Any]:
    return {
        "category": category,
        "index": index,
        "system": prompt.system,
        "user": prompt.user,
    }


def main() -> None:
    args = parse_args()
    sys.argv = [sys.argv[0]]

    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    icon_settings_json, icon_trials = load_study(Path(args.iconoclast_checkpoint))
    her_settings_json, her_trials = load_study(Path(args.heretic_checkpoint))
    icon_best = pick_best_trial(icon_trials)
    her_best = pick_best_trial(her_trials)

    icon_stack = load_stack("iconoclast")
    her_stack = load_stack("heretic")

    icon_runtime = prepare_runtime(icon_stack, icon_settings_json)
    her_runtime = prepare_runtime(her_stack, her_settings_json)

    sample_count = args.sample_count
    sample_prompts = [
        prompt_record("harmful", i, prompt)
        for i, prompt in enumerate(icon_runtime["bad_eval_prompts"][:sample_count])
    ] + [
        prompt_record("harmless", i, prompt)
        for i, prompt in enumerate(icon_runtime["good_eval_prompts"][:sample_count])
    ]

    base_runtime = prepare_runtime(icon_stack, icon_settings_json)
    base_prompts = [
        icon_stack["utils"].Prompt(system=item["system"], user=item["user"])
        for item in sample_prompts
    ]
    base_responses = base_runtime["model"].get_responses_batched(
        base_prompts,
        skip_special_tokens=True,
    )

    apply_trial(icon_runtime, icon_best)
    export_merged_model(icon_runtime, output_dir / "iconoclast-best-merged")
    icon_responses = icon_runtime["model"].get_responses_batched(
        base_prompts,
        skip_special_tokens=True,
    )

    apply_trial(her_runtime, her_best)
    export_merged_model(her_runtime, output_dir / "heretic-best-merged")
    her_responses = her_runtime["model"].get_responses_batched(
        base_prompts,
        skip_special_tokens=True,
    )

    refusal_markers = icon_runtime["settings"].refusal_markers
    comparisons = []
    for item, base_response, icon_response, her_response in zip(
        sample_prompts,
        base_responses,
        icon_responses,
        her_responses,
    ):
        comparisons.append(
            {
                **item,
                "base": {
                    "refusal": is_refusal(base_response, refusal_markers),
                    "response": base_response,
                },
                "iconoclast": {
                    "refusal": is_refusal(icon_response, refusal_markers),
                    "response": icon_response,
                },
                "heretic": {
                    "refusal": is_refusal(her_response, refusal_markers),
                    "response": her_response,
                },
            }
        )

    summary = {
        "base_model": icon_runtime["settings"].model,
        "iconoclast_best": icon_best,
        "heretic_best": her_best,
        "comparison_sample_count_per_split": sample_count,
        "comparisons": comparisons,
    }

    (output_dir / "comparison.json").write_text(json.dumps(summary, indent=2))
    (output_dir / "summary.json").write_text(
        json.dumps(
            {
                "base_model": summary["base_model"],
                "iconoclast_best": icon_best,
                "heretic_best": her_best,
            },
            indent=2,
        )
    )

    print(json.dumps(summary["iconoclast_best"], indent=2))
    print(json.dumps(summary["heretic_best"], indent=2))
    print(f"Wrote exports and comparison to {output_dir}")


if __name__ == "__main__":
    os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
    main()