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
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
#!/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


CREST_SYSTEM = (
    "Answer the following questions. You should think step-by-step "
    "and put your final answer within \\boxed{}."
)


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": "system", "content": CREST_SYSTEM},
        {"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 CREST_SYSTEM + "\n\n" + problem


def first_complete_boxed_end(text):
    i = text.find("\\boxed")
    if i < 0:
        return None
    j = text.find("{", i)
    if j < 0:
        return None
    depth = 0
    for k in range(j, len(text)):
        if text[k] == "{":
            depth += 1
        elif text[k] == "}":
            depth -= 1
            if depth == 0:
                return k + 1
    return None


def truncate_after_first_boxed(text):
    end = first_complete_boxed_end(text)
    return text[:end] if end is not None else text


def last_boxed(text):
    if not text:
        return None
    i = text.rfind("\\boxed")
    if i < 0:
        return None
    j = text.find("{", i)
    if j < 0:
        return None
    depth = 0
    for k in range(j, len(text)):
        if text[k] == "{":
            depth += 1
        elif text[k] == "}":
            depth -= 1
            if depth == 0:
                return text[j + 1:k].strip()
    return None


class StopAfterFirstBoxedMath(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 first_complete_boxed_end(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):
        if input_ids.shape[-1] > 1:
            self.active = False
            self.prefill_done = True
            return
        tail = self.tokenizer.decode(input_ids[0][-8:], skip_special_tokens=False)
        self.active = tail.endswith("\n\n") or tail.endswith("\n \n")


def _norm(s):
    if s is None:
        return ""
    t = str(s).strip()
    for x in ["\\left", "\\right", "\\!", "\\,", "\\;", "$", " "]:
        t = t.replace(x, "")
    return t.lower()


def _as_int(s):
    if s is None:
        return None
    t = re.sub(r"[^\d\-]", "", str(s))
    try:
        return int(t)
    except Exception:
        return None


def _as_float(s):
    if s is None:
        return None
    try:
        return float(str(s).replace(",", "").replace("$", ""))
    except Exception:
        return None


def _latex_to_sympy_src(s):
    t = str(s)
    t = t.replace("\\dfrac", "\\frac")
    t = re.sub(r"\\frac\{([^{}]+)\}\{([^{}]+)\}", r"((\1)/(\2))", t)
    t = re.sub(r"\\sqrt\{([^{}]+)\}", r"sqrt(\1)", t)
    t = re.sub(r"\\sqrt\s*(\d+)", r"sqrt(\1)", t)
    t = t.replace("\\cdot", "*").replace("\\times", "*")
    t = t.replace("^", "**")
    t = re.sub(r"\\pi\b", "pi", t)
    t = re.sub(r"\\(left|right|!|,|;|:)", "", t)
    t = re.sub(r"\\[a-zA-Z]+", "", t)
    t = t.replace("{", "(").replace("}", ")").replace("$", "")
    return t


def _sympy_eq(a, b):
    try:
        from sympy import sympify, simplify
    except ImportError:
        return None
    try:
        pa = sympify(_latex_to_sympy_src(a))
        pb = sympify(_latex_to_sympy_src(b))
        return bool(simplify(pa - pb) == 0)
    except Exception:
        return None


def is_correct(pred, gold):
    if pred is None or gold is None or not str(gold).strip():
        return False
    p, g = str(pred).strip(), str(gold).strip()
    if p == g:
        return True
    pi, gi = _as_int(p), _as_int(g)
    if pi is not None and gi is not None and "/" not in p and "/" not in g:
        return pi == gi
    pf, gf = _as_float(p), _as_float(g)
    if pf is not None and gf is not None and abs(pf) < 1e9 and abs(gf) < 1e9:
        if abs(pf - gf) < 1e-6:
            return True
    sym = _sympy_eq(p, g)
    if sym is not None:
        return sym
    np_, ng_ = _norm(p), _norm(g)
    return np_ == ng_ and np_ != ""


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=0)
    ap.add_argument("--lambda-weight", type=float, default=-0.48)
    ap.add_argument("--layers", default="6-47")
    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)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(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-MATH500] model_path       = {args.model_path}", flush=True)
    print(f"[ReflCtrl-MATH500] data             = {args.data}", flush=True)
    print(f"[ReflCtrl-MATH500] direction        = {args.direction_path}", flush=True)
    print(f"[ReflCtrl-MATH500] out              = {args.out}", flush=True)
    print(f"[ReflCtrl-MATH500] n                = {len(rows)}", flush=True)
    print(f"[ReflCtrl-MATH500] seed             = {args.seed}", flush=True)
    print(f"[ReflCtrl-MATH500] lambda           = {args.lambda_weight}", flush=True)
    print(f"[ReflCtrl-MATH500] layers           = {args.layers}", flush=True)
    print(f"[ReflCtrl-MATH500] max_new_tokens   = {args.max_new_tokens}", flush=True)
    print(f"[ReflCtrl-MATH500] temperature      = {args.temperature}", flush=True)
    print(f"[ReflCtrl-MATH500] top_p            = {args.top_p}", flush=True)
    print(f"[ReflCtrl-MATH500] stop_after_boxed = {args.stop_after_boxed}", flush=True)
    print(f"[ReflCtrl-MATH500] 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") or "").strip()

            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([StopAfterFirstBoxedMath(tokenizer, input_len)])

            state.active = False
            state.prefill_done = False

            gen_seed = args.seed * 1000 + i
            torch.manual_seed(gen_seed)
            if torch.cuda.is_available():
                torch.cuda.manual_seed_all(gen_seed)

            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(cot)

            pred = last_boxed(cot)
            correct = is_correct(pred, gt)
            ttok = think_tokens_like_crest(tokenizer, cot)
            rep = repetition_score(cot)
            mtot = mon_total(cot)
            elapsed = time.time() - t0
            has_boxed = pred is not None
            collapse = (not has_boxed) or rep >= 0.5 or ttok >= args.max_new_tokens

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

            print(
                f"P{i}_ReflCtrl_lam{args.lambda_weight:+.2f} "
                f"pred={pred} gt={gt} {'OK' if correct else 'BAD'} "
                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()