File size: 10,529 Bytes
f6c2fe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
import argparse
import json
import re
import time
from pathlib import Path

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers import StoppingCriteria, StoppingCriteriaList


BOXED_CHOICE_RE = re.compile(r"\\boxed\s*\{\s*([ABCD])\s*\}")


class StopAfterFirstBoxedChoice(StoppingCriteria):
    def __init__(self, tokenizer, prompt_len):
        self.tokenizer = tokenizer
        self.prompt_len = prompt_len

    def __call__(self, input_ids, scores, **kwargs):
        gen_text = self.tokenizer.decode(input_ids[0][self.prompt_len:], skip_special_tokens=True)
        return BOXED_CHOICE_RE.search(gen_text) is not None


class StepwiseState:
    def __init__(self, tokenizer):
        self.tokenizer = tokenizer
        self.active = False
        self.prefill_done = False

    def update_from_input_ids(self, input_ids):
        # During prefill, do not intervene.
        if input_ids.shape[-1] > 1:
            self.active = False
            self.prefill_done = True
            return

        # During autoregressive decoding, intervene only when previous token ended a step.
        tail = self.tokenizer.decode(input_ids[0][-8:], skip_special_tokens=False)
        self.active = tail.endswith("\n\n") or tail.endswith("\n \n")


def read_jsonl(path):
    rows = []
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            if line.strip():
                rows.append(json.loads(line))
    return rows


def append_jsonl(path, obj):
    with open(path, "a", encoding="utf-8") as f:
        f.write(json.dumps(obj, ensure_ascii=False) + "\n")


def build_prompt(tokenizer, problem):
    messages = [{"role": "user", "content": problem}]
    if hasattr(tokenizer, "apply_chat_template") and tokenizer.chat_template is not None:
        return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    return problem


def extract_first_boxed_choice(text):
    m = BOXED_CHOICE_RE.search(text)
    return m.group(1) if m else None


def truncate_after_first_boxed_choice(text):
    m = BOXED_CHOICE_RE.search(text)
    return text[:m.end()] if m else text


def think_tokens_like_crest(tokenizer, cot):
    seg = cot.split("</think>", 1)[0] if "</think>" in cot else cot
    return len(tokenizer.encode(seg, add_special_tokens=False))


def repetition_score(text, n=40):
    if not text:
        return 0.0
    chunks = [text[i:i+n] for i in range(0, max(0, len(text) - n + 1), n)]
    if not chunks:
        return 0.0
    counts = {}
    for c in chunks:
        counts[c] = counts.get(c, 0) + 1
    return max(counts.values()) / max(1, len(chunks))


def mon_total(text):
    markers = [
        "wait", "Wait", "check", "Check", "rethink", "Rethink",
        "however", "However", "maybe", "Maybe", "alternatively",
        "Actually", "actually", "Let's verify", "verify",
    ]
    return sum(text.count(m) for m in markers)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data", required=True)
    ap.add_argument("--model-path", required=True)
    ap.add_argument("--direction-path", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--seed", type=int, default=64)
    ap.add_argument("--lambda-weight", type=float, default=-0.48)
    ap.add_argument("--layers", default="6-57")
    ap.add_argument("--max-new-tokens", type=int, default=32768)
    ap.add_argument("--temperature", type=float, default=0.6)
    ap.add_argument("--top-p", type=float, default=0.95)
    ap.add_argument("--limit", type=int, default=None)
    ap.add_argument("--force", action="store_true")
    ap.add_argument("--stop-after-boxed", action="store_true")
    args = ap.parse_args()

    torch.manual_seed(args.seed)

    out_path = Path(args.out)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    if args.force and out_path.exists():
        out_path.unlink()

    rows = read_jsonl(args.data)
    if args.limit is not None:
        rows = rows[:args.limit]

    existing = set()
    if out_path.exists():
        for line in out_path.read_text(encoding="utf-8").splitlines():
            if line.strip():
                existing.add(json.loads(line).get("_key"))

    l0, l1 = [int(x) for x in args.layers.split("-")]
    layers = list(range(l0, l1 + 1))

    print(f"[ReflCtrl] model_path       = {args.model_path}", flush=True)
    print(f"[ReflCtrl] data             = {args.data}", flush=True)
    print(f"[ReflCtrl] direction        = {args.direction_path}", flush=True)
    print(f"[ReflCtrl] out              = {args.out}", flush=True)
    print(f"[ReflCtrl] n                = {len(rows)}", flush=True)
    print(f"[ReflCtrl] seed             = {args.seed}", flush=True)
    print(f"[ReflCtrl] lambda           = {args.lambda_weight}", flush=True)
    print(f"[ReflCtrl] layers           = {args.layers}", flush=True)
    print(f"[ReflCtrl] max_new_tokens   = {args.max_new_tokens}", flush=True)
    print(f"[ReflCtrl] temperature      = {args.temperature}", flush=True)
    print(f"[ReflCtrl] top_p            = {args.top_p}", flush=True)
    print(f"[ReflCtrl] stop_after_boxed = {args.stop_after_boxed}", flush=True)
    print(f"[ReflCtrl] existing records = {len(existing)}", flush=True)

    tokenizer = AutoTokenizer.from_pretrained(args.model_path, trust_remote_code=True, use_fast=True)
    if tokenizer.pad_token_id is None:
        tokenizer.pad_token = tokenizer.eos_token

    model = AutoModelForCausalLM.from_pretrained(
        args.model_path,
        trust_remote_code=True,
        torch_dtype="auto",
        device_map="auto",
    )
    model.eval()

    ckpt = torch.load(args.direction_path, map_location="cpu")
    components = ckpt["components"]

    state = StepwiseState(tokenizer)

    original_forward = model.forward

    def wrapped_forward(*f_args, **f_kwargs):
        input_ids = f_kwargs.get("input_ids", None)
        if input_ids is None and len(f_args) > 0:
            input_ids = f_args[0]
        if input_ids is not None:
            state.update_from_input_ids(input_ids)
        return original_forward(*f_args, **f_kwargs)

    model.forward = wrapped_forward

    handles = []

    def make_hook(name):
        vec = components[name]["mean_diff"].float()
        def hook(module, inputs, output):
            if not state.active:
                return output
            h = output[0] if isinstance(output, tuple) else output
            v = vec.to(device=h.device, dtype=h.dtype)
            h2 = h.clone()
            h2[:, -1, :] = h2[:, -1, :] + args.lambda_weight * v
            if isinstance(output, tuple):
                return (h2,) + output[1:]
            return h2
        return hook

    for l in layers:
        for suffix, module in [
            ("self_attn", model.model.layers[l].self_attn),
            ("mlp", model.model.layers[l].mlp),
        ]:
            name = f"model.layers[{l}].{suffix}"
            if name in components:
                handles.append(module.register_forward_hook(make_hook(name)))
            else:
                print(f"[WARN] missing direction component: {name}", flush=True)

    first_device = next(model.parameters()).device

    try:
        for i, item in enumerate(rows):
            key = f"P{i}_ReflCtrl_lam{args.lambda_weight:+.2f}".replace("+", "p").replace("-", "m").replace(".", "p")
            if key in existing:
                print(f"[SKIP] {key}", flush=True)
                continue

            problem = item.get("problem") or item.get("question") or item.get("prompt")
            if problem is None:
                raise KeyError(f"missing problem/question/prompt at row {i}")

            gt = str(item.get("answer") or item.get("gt") or item.get("label")).strip().upper()
            if gt and gt[0] in "ABCD":
                gt = gt[0]

            prompt = build_prompt(tokenizer, problem)
            inputs = tokenizer(prompt, return_tensors="pt")
            inputs = {k: v.to(first_device) for k, v in inputs.items()}
            input_len = inputs["input_ids"].shape[-1]

            stopping = None
            if args.stop_after_boxed:
                stopping = StoppingCriteriaList([StopAfterFirstBoxedChoice(tokenizer, input_len)])

            state.active = False
            state.prefill_done = False

            t0 = time.time()
            with torch.no_grad():
                out = model.generate(
                    **inputs,
                    max_new_tokens=args.max_new_tokens,
                    do_sample=True,
                    temperature=args.temperature,
                    top_p=args.top_p,
                    pad_token_id=tokenizer.pad_token_id,
                    eos_token_id=tokenizer.eos_token_id,
                    stopping_criteria=stopping,
                )

            gen_ids = out[0][input_len:]
            cot = tokenizer.decode(gen_ids, skip_special_tokens=True)
            if args.stop_after_boxed:
                cot = truncate_after_first_boxed_choice(cot)

            pred = extract_first_boxed_choice(cot)
            correct = pred == gt if pred is not None and gt else False
            ttok = think_tokens_like_crest(tokenizer, cot)
            rep = repetition_score(cot)
            mtot = mon_total(cot)
            elapsed = time.time() - t0

            collapse = pred is None or rep >= 0.50 or ttok >= args.max_new_tokens - 8

            rec = {
                "_key": key,
                "method": "ReflCtrl",
                "problem_idx": i,
                "lambda": args.lambda_weight,
                "layers": args.layers,
                "seed": args.seed,
                "problem": problem,
                "cot": cot,
                "pred": pred,
                "gt": gt,
                "correct": correct,
                "has_boxed": pred is not None,
                "think_tokens": ttok,
                "n_chars": len(cot),
                "mon_total": mtot,
                "repetition_score": rep,
                "collapse": collapse,
                "elapsed_s": elapsed,
            }
            append_jsonl(out_path, rec)

            status = "OK" if correct else "BAD"
            print(
                f"{key} pred={pred} gt={gt} {status} "
                f"tok={ttok} mon={mtot} rep={rep:.2f} "
                f"collapse={collapse} t={elapsed:.1f}s",
                flush=True,
            )

    finally:
        for h in handles:
            h.remove()


if __name__ == "__main__":
    main()